"매 graph traversal 의 두 fundamental order: queue (BFS) vs stack (DFS)". 매 1959 Moore 의 BFS, 매 1882 Trémaux 의 DFS-like maze. 매 modern algo 의 building block — 매 shortest path, topological sort, cycle detection 의 base.
매 핵심
매 BFS
queue (FIFO) 의 사용 — 매 level-by-level expansion.
shortest path 의 unweighted graph 의 guarantee (edge count 기준).
매 시간: O(V + E), 매 공간: O(V) (queue + visited).
매 응용: shortest hop, level traversal, bipartite check, web crawl (per-depth limit).
매 DFS
stack (LIFO) / recursion 의 사용 — 매 deep dive first.
shortest path 의 X — 매 tree edge order 의 의 의.
매 시간: O(V + E), 매 공간: O(V) (recursion stack / explicit stack).
매 응용: cycle detection, topological sort, SCC (Tarjan/Kosaraju), maze solving.
매 trade-off
Aspect
BFS
DFS
Memory
O(b^d) — wide tree 의 explode
O(b·d) — deep stack
Path
shortest (unweighted)
any reachable
Implementation
queue + iterative
recursion / explicit stack
Backtracking
hard
natural
매 응용 differential
shortest path (unweighted) → BFS.
shortest path (weighted) → Dijkstra (BFS의 generalization, 매 priority queue).
defdfs_iter(graph,start):stack,visited,order=[start],set(),[]whilestack:node=stack.pop()ifnodeinvisited:continuevisited.add(node)order.append(node)# reverse for same order as recursivefornbinreversed(graph[node]):ifnbnotinvisited:stack.append(nb)returnorder
WHITE,GRAY,BLACK=0,1,2defhas_cycle(graph):color={n:WHITEforningraph}defdfs(n):color[n]=GRAYfornbingraph[n]:ifcolor[nb]==GRAY:returnTrue# back edgeifcolor[nb]==WHITEanddfs(nb):returnTruecolor[n]=BLACKreturnFalsereturnany(dfs(n)forningraphifcolor[n]==WHITE)
매 결정 기준
상황
Approach
shortest path (unweighted)
BFS
shortest path (weighted)
Dijkstra / A*
topological sort
DFS post-order / Kahn
cycle detection
DFS color
memory tight, deep tree
DFS
memory ample, wide goals
BFS
매 path enumeration / backtrack
DFS
매 web crawl (depth-limited)
BFS with depth
기본값: shortest path 의 BFS, 매 structural analysis (topo, cycle, SCC) 의 DFS.
언제: 매 graph 문제 의 first-cut, 매 grid maze, 매 dependency resolution, 매 social network expansion.
언제 X: 매 weighted shortest path (Dijkstra), 매 heuristic 가능 시 (A*), 매 huge graph 의 sampling (random walk).
❌ 안티패턴
BFS의 memory: 매 huge branching factor → O(b^d) 의 OOM. 매 IDDFS 의 의 의.
DFS recursion limit: Python 의 default 1000 — 매 large graph 의 stack overflow. 매 iterative 의 의.
visited X: 매 cycle 의 infinite loop.
BFS의 path 의 다 저장: O(V²) memory — 매 parent map 의 의 reconstruct.