[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,93 +2,185 @@
|
||||
id: wiki-2026-0508-bfs-vs-dfs
|
||||
title: BFS vs DFS
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-BDFS-001]
|
||||
aliases: [Breadth-First vs Depth-First, 너비 우선 vs 깊이 우선]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.99
|
||||
tags: [auto-reinforced, bfs, dfs, algorithms, graph-Search, tree-traversal, Problem-Solving]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [algorithms, graph, traversal, bfs, dfs, search]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: none
|
||||
---
|
||||
|
||||
# [[BFS vs DFS|BFS vs DFS]]
|
||||
# BFS vs DFS
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "지식 탐색의 두 가지 갈래: 현재 층위의 모든 가능성을 먼저 훑으며 최단 경로를 찾는 '발 넓은' 너비 우선 탐색(BFS)과, 한 가지 가능성을 끝까지 파고들어 바닥을 확인하는 '집요한' 깊이 우선 탐색(DFS)의 지적 대비."
|
||||
## 매 한 줄
|
||||
> **"매 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.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
너비 우선 탐색(BFS)과 깊이 우선 탐색(DFS)은 그래프나 트리 구조를 순회하는 가장 기초적인 알고리즘입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **BFS (Breadth-First Search)**:
|
||||
* **동작**: 루트 노드에서 가까운 노드부터 차례대로 방문 (Queue 사용).
|
||||
* **장점**: 최단 경로(Shortest path)를 찾는 데 최적임.
|
||||
* **단점**: 모든 자식 노드를 메모리에 담아야 하므로 공간 복잡도가 높음.
|
||||
2. **DFS (Depth-First Search)**:
|
||||
* **동작**: 한 분기를 결정하면 그 분기의 끝(Leaf)까지 가본 후 뒤로 돌아옴 (Stack 또는 Recursion 사용).
|
||||
* **장점**: 메모리 가성비가 좋고, 경로상에 정답이 깊이 있을 때 유리함.
|
||||
* **단점**: 얻은 경로가 최단 경로라는 보장이 없으며 무한 루프 위험이 있음. ([[Backward-Reasoning|Backward-Reasoning]]과 연결)
|
||||
### 매 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).
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 문제 유형에 따라 하나를 선택하는 정적인 알고리즘 정책이었으나, 현대 AI 정책(MCTS 등)은 두 방식을 확률적으로 혼합하거나 보상에 따라 동적으로 깊이와 너비를 결정하는 '적응적 탐색 정책'으로 진화함(RL Update).
|
||||
- **정책 변화(RL Update)**: 거대 언어 모델의 생각의 사슬(Chain of Thought) 추론 정책에서, 하나의 답변에 함몰되지 않고 여러 가지 추론 가지를 BFS적으로 생성해 비교하는 'Tree-of-Thoughts' 기법이 고난도 문제 해결의 핵심 정책이 됨.
|
||||
### 매 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.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Binary-Search|Binary-Search]], [[Backward-Reasoning|Backward-Reasoning]], [[Search-Optimization|Search-Optimization]], [[Analysis|Analysis]], Pattern Recognition
|
||||
- **Modern Tech/Tools**: Pathfinding algorithms in GPS, Crawling bots, Game AI (Minimax).
|
||||
---
|
||||
### 매 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 |
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용 differential
|
||||
1. **shortest path (unweighted)** → BFS.
|
||||
2. **shortest path (weighted)** → Dijkstra (BFS의 generalization, 매 priority queue).
|
||||
3. **topological sort** → DFS (post-order reverse) / Kahn's BFS.
|
||||
4. **cycle detection** → DFS (back edge) / BFS (in-degree).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### BFS basic
|
||||
```python
|
||||
from collections import deque
|
||||
from typing import Dict, List, Set
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def bfs(graph: Dict[int, List[int]], start: int) -> List[int]:
|
||||
visited: Set[int] = {start}
|
||||
queue = deque([start])
|
||||
order = []
|
||||
while queue:
|
||||
node = queue.popleft()
|
||||
order.append(node)
|
||||
for nb in graph[node]:
|
||||
if nb not in visited:
|
||||
visited.add(nb)
|
||||
queue.append(nb)
|
||||
return order
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### BFS shortest path (unweighted)
|
||||
```python
|
||||
def bfs_shortest(graph, start, target):
|
||||
queue = deque([(start, [start])])
|
||||
visited = {start}
|
||||
while queue:
|
||||
node, path = queue.popleft()
|
||||
if node == target:
|
||||
return path
|
||||
for nb in graph[node]:
|
||||
if nb not in visited:
|
||||
visited.add(nb)
|
||||
queue.append((nb, path + [nb]))
|
||||
return None # unreachable
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### DFS recursive
|
||||
```python
|
||||
def dfs(graph, node, visited=None, order=None):
|
||||
if visited is None: visited, order = set(), []
|
||||
visited.add(node)
|
||||
order.append(node)
|
||||
for nb in graph[node]:
|
||||
if nb not in visited:
|
||||
dfs(graph, nb, visited, order)
|
||||
return order
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### DFS iterative (avoids recursion limit)
|
||||
```python
|
||||
def dfs_iter(graph, start):
|
||||
stack, visited, order = [start], set(), []
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if node in visited: continue
|
||||
visited.add(node)
|
||||
order.append(node)
|
||||
# reverse for same order as recursive
|
||||
for nb in reversed(graph[node]):
|
||||
if nb not in visited:
|
||||
stack.append(nb)
|
||||
return order
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Topological sort (DFS post-order)
|
||||
```python
|
||||
def topo_sort(graph):
|
||||
visited, order = set(), []
|
||||
def visit(n):
|
||||
if n in visited: return
|
||||
visited.add(n)
|
||||
for nb in graph[n]: visit(nb)
|
||||
order.append(n) # post-order
|
||||
for n in graph: visit(n)
|
||||
return order[::-1]
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Cycle detection (DFS with color)
|
||||
```python
|
||||
WHITE, GRAY, BLACK = 0, 1, 2
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
def has_cycle(graph):
|
||||
color = {n: WHITE for n in graph}
|
||||
def dfs(n):
|
||||
color[n] = GRAY
|
||||
for nb in graph[n]:
|
||||
if color[nb] == GRAY: return True # back edge
|
||||
if color[nb] == WHITE and dfs(nb): return True
|
||||
color[n] = BLACK
|
||||
return False
|
||||
return any(dfs(n) for n in graph if color[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
|
||||
- 부모: [[Graph Theory]] · [[Search Algorithms]]
|
||||
- 변형: [[Bidirectional Search]] · [[Iterative Deepening]] · [[Beam Search]]
|
||||
- 응용: [[Dijkstra's Algorithm]] · [[A-Star Pathfinding]] · [[Topological Sort]] · [[Connected Components]]
|
||||
- Adjacent: [[Tree Traversal]] · [[Tarjan SCC]] · [[Kosaraju Algorithm]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 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.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (CLRS Ch 22; Sedgewick Algorithms 4th).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — BFS/DFS comparison with topo sort + cycle detection patterns |
|
||||
|
||||
Reference in New Issue
Block a user