d 정도 쉽게 말하면, “한 길을 끝까지 파고 내려가면서 그 길만 기억”하는 느낌
w 정도 쉽게 말하면, “한 층에 있는 모든 노드를 한꺼번에 기억”하는 느낌
| 탐색 방식 | 자료구조 | 최대 저장 노드 수 | 공간 특징 |
|---|---|---|---|
| DFS | 스택/재귀 | 최대 그래프 깊이 d | 깊이가 낮으면 공간 적게 사용 |
| BFS | 큐 | 최대 레벨 너비 w | 레벨이 넓으면 공간 많이 사용 |
즉, 같은 그래프라도 DFS는 한 경로만, BFS는 한 레벨 전체를 저장하기 때문에 공간 사용 패턴이 다르다.
문제 상황에 맞게 DFS와 BFS를 선택하면 효율적으로 탐색할 수 있다.
DFS는 크게 재귀 함수 방식과 스택을 활용한 반복문 방식으로 구현할 수 있습니다.
def dfs_stack(adjacent_graph, start_node):
stack = [start_node]
visited = []
while stack:
current_node = stack.pop()
if current_node not in visited: # 방문 체크 필요
visited.append(current_node)
# 인접 노드를 stack에 추가
for adjacent_node in adjacent_graph[current_node]:
if adjacent_node not in visited:
stack.append(adjacent_node)
return visited
print(dfs_stack(graph, 1))
✅ 특징
def dfs_stack(adjacent_graph, start_node):
stack = [start_node]
visited = []
while stack:
current_node = stack.pop()
visited.append(current_node)
for adjacent_node in adjacent_graph[current_node]:
if adjacent_node not in visited:
stack.append(adjacent_node)
return visited
print(dfs_stack(graph, 1))
✅ 특징
📌 DFS 구현 방식 비교
방식 장점 단점 재귀 DFS 코드가 간단하고 직관적 깊이 제한 존재 → RecursionError발생 가능스택 DFS 깊이 제한 없음, 메모리 효율적 코드가 재귀보다 조금 길어짐
BFS(Breadth-First Search)는 한 레벨씩 너비 우선으로 탐색하는 방법입니다.
보통 큐(Queue) 자료구조를 이용해서 구현합니다.
from collections import deque
graph = {
1: [2, 3, 4],
2: [1, 5],
3: [1, 6, 7],
4: [1, 8],
5: [2, 9],
6: [3, 10],
7: [3],
8: [4],
9: [5],
10: [6]
}
def bfs_queue(adj_graph, start_node):
queue = deque()
visited = []
queue.append(start_node)
while queue:
current_node = queue.popleft()
for adj_node in adj_graph[current_node]:
if adj_node not in visited:
visited.append(adj_node)
queue.append(adj_node)
return visited
print(bfs_queue(graph, 1))
✅ 특징
📌 요약