1.BFS 너비 우선 탐색 (Breadth-First Search)
- BFS : 주변에 있는 노드를 탐색하며 탐색 범위 확장 (queue활용해서 구현)
- 루트노드부터 주변노드까지 쭉 탐색후 더 깊숙히 탐색
- 예시)자동사냥 : 가장 가까운 적 공격, 추적반경 계산에 사용
2.DFS 깊이 우선 탐색 (Depth-First Search)
- 루트노드부터 시작하여 한쪽 방향을 다 본다음에 다른방향 탐색
- Stack혹은 재귀 사용하여 구현 가능
- 예시) 미로 찾기, 모든 경우의 수 찾기
3. BFS와 DFS의 차이 표

4. 코드 구현
동영상 강좌 참조
public class Node<T>
{
public T Value { get; set; }
public List<Node<T>> Neighbors { get; private set; }
public Node(T value)
{
Neighbors = new List<Node<T>>();
Value = value;
}
}
public class SimpleGraph<T>
{
List<Node<T>> nodes = new List<Node<T>>();
public Node<T> AddNode(T value)
{
Node<T> node = new Node<T>(value);
nodes.Add(node);
return node;
}
public void AddEdge(Node<T> from, Node<T> to)
{
from.Neighbors.Add(to);
}
public void AddUndirectedEdge(Node<T> a, Node<T> b)
{
a.Neighbors.Add(b);
b.Neighbors.Add(a);
}
public void PrintGraph()
{
foreach (var node in nodes)
{
Console.Write($"{node.Value} -> ");
foreach (var edge in node.Neighbors)
{
Console.Write($"{edge.Value} ");
}
Console.WriteLine();
}
}
public void BFS(Node<T> start, Node<T> target)
{
Queue<Node<T>> queue = new Queue<Node<T>>();
List<Node<T>> visited = new List<Node<T>>();
queue.Enqueue(start);
while(queue.Count > 0)
{
Node<T> current = queue.Dequeue();
if(visited.Contains(current))
{
continue;
}
Console.WriteLine($"지하철역 방문: {current.Value}");
visited.Add(current);
if(current.Equals(target))
{
Console.WriteLine($"목표 역{target.Value} 발견!");
return;
}
foreach(var neighbor in current.Neighbors)
{
if(visited.Contains(neighbor)== false)
{
queue.Enqueue(neighbor);
}
}
}
Console.WriteLine("경로 탐색 실패");
}
public void DFS(Node<T> start, Node<T> target)
{
Stack<Node<T>> stack = new Stack<Node<T>>();
List<Node<T>> visited = new List<Node<T>>();
stack.Push(start);
while (stack.Count > 0)
{
Node<T> current = stack.Pop();
if (visited.Contains(current))
{
continue;
}
Console.WriteLine($"지하철역 방문: {current.Value}");
visited.Add(current);
if (current.Equals(target))
{
Console.WriteLine($"목표 역{target.Value} 발견!");
return;
}
foreach (var neighbor in current.Neighbors)
{
if (visited.Contains(neighbor) == false)
{
stack.Push(neighbor);
}
}
}
Console.WriteLine("경로 탐색 실패");
}
}
class Program
{
static void Main(string[] args)
{
SimpleGraph<string> subway = new SimpleGraph<string>();
var Gwangnaru = subway.AddNode("광나루");
var CheonHo = subway.AddNode("천호역");
var GangDong = subway.AddNode("강동역");
var GilDong = subway.AddNode("길동");
var DunChonDong = subway.AddNode("둔촌동");
var OlympicPark = subway.AddNode("올림픽공원역");
subway.AddUndirectedEdge(CheonHo, GangDong);
subway.AddUndirectedEdge(GangDong, DunChonDong);
subway.AddUndirectedEdge(GangDong, GilDong);
subway.AddUndirectedEdge(DunChonDong, OlympicPark);
subway.AddUndirectedEdge(CheonHo, Gwangnaru);
subway.PrintGraph();
subway.BFS(CheonHo, OlympicPark);
subway.DFS(CheonHo, OlympicPark);
}
}
5. 코드 구현 (가중치 추가) -> 추가예정