DSA & CS / 6. GRAPHS & BFS/DFS
Graphs & BFS / DFS
Networks, paths, and connected components
EXPLANATION
A graph is a set of nodes (vertices) connected by edges. Unlike trees, graphs can have cycles, multiple paths, and disconnected components. Representations: • Adjacency List → dict mapping node to list of neighbors. Space O(V+E). Best for sparse graphs • Adjacency Matrix → 2D array. Space O(V²). Good for dense graphs, O(1) edge lookup DFS (Depth-First Search): go as deep as possible before backtracking. → Uses stack (recursion call stack or explicit) → Good for: cycle detection, topological sort, connected components, paths BFS (Breadth-First Search): explore all neighbors before going deeper. → Uses queue → Good for: shortest path (unweighted), level-order, minimum steps Key graph problems: • Number of islands → DFS/BFS flood fill • Clone graph → DFS with visited map • Course schedule → topological sort / cycle detection • Word ladder → BFS shortest path • Dijkstra → shortest path in weighted graph
DIAGRAM
Graph (adjacency list): 0 → [1, 2] 1 → [0, 3] 2 → [0, 4] 3 → [1] 4 → [2] DFS from 0: 0 → 1 → 3 → (back) → (back) → 2 → 4 Visit order: 0, 1, 3, 2, 4 BFS from 0: Level 0: [0] Level 1: [1, 2] ← neighbors of 0 Level 2: [3, 4] ← neighbors of 1 and 2 Visit order: 0, 1, 2, 3, 4 ← shortest path!
CODE