BFS(Breadth-First Search, 너비 우선 탐색)는 시작 정점에서 인접한 노드를 먼저 탐색하고,
그 다음 레벨의 노드를 탐색해 나가는 방식의 알고리즘이다.
탐색의 흐름이 큐(Queue) 구조를 따른다.
A
/ \
B C
/ \
D E
레벨 순회 결과: A → B → C → D → E
from collections import deque
def level_order(root):
if not root:
return
queue = deque([root])
while queue:
node = queue.popleft()
print(node.key, end=' ')
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# 트리 생성
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
root = Node('A')
root.left = Node('B')
root.right = Node('C')
root.left.left = Node('D')
root.left.right = Node('E')
level_order(root) # 출력: A B C D E
→ 큐를 중심으로 한 단계씩 확장해나가는 탐색
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=' ')
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
graph = {
0: [1, 2],
1: [0, 3, 4],
2: [0],
3: [1],
4: [1]
}
bfs(graph, 0) # 출력: 0 1 2 3 4
항목 | 그래프 BFS | 트리 BFS (레벨 순회) |
---|---|---|
방문 배열 | 필요 ✅ | 필요 ❌ (사이클 없음) |
탐색 방식 | 연결된 모든 노드 큐 삽입 | 왼쪽 → 오른쪽 자식 순서로 큐 삽입 |
응용 | 최단 거리, 연결 요소, 경로 | 레벨 기반 처리, 트리 시각화 |
깊이 우선성 | 없음 | 레벨 우선이므로 루트와 가까운 노드부터 탐색 |
시간 복잡도 | O(V + E) | O(N) |