def dfs(graph, start): visited = [False] * len(graph) # WHY: prevent revisiting / infinite loops def explore(u): visited[u] = True # WHY: mark BEFORE recursing, else cycles re-enter process(u) # pre-order: do work on entry for v in graph[u]: # scan adjacency list -> deg(u) work if not visited[v]: # WHY: only descend into new nodes explore(v) # recurse deep first explore(start)
def dfs_iter(graph, start): visited = [False] * len(graph) stack = [start] while stack: u = stack.pop() # LIFO -> depth-first if visited[u]: # WHY: a node can be pushed twice before popping continue visited[u] = True process(u) for v in graph[u]: if not visited[v]: stack.append(v) # push neighbors; deepest explored next
You're exploring a cave with tunnels. You walk into one tunnel and keep going deeper until it dead-ends. Then you walk back to the last fork and try a tunnel you haven't been in. You drop a glowstick in every room you enter (that's the visited array) so you never re-explore a room or get stuck walking in circles. Because you drop exactly one glowstick per room and walk down each tunnel a fixed number of times, the whole trip takes time proportional to (rooms + tunnels) — fast!
DFS ka matlab hai Depth-First Search — yaani kisi bhi ek raaste mein "andar tak ghus jao" jab tak dead-end na aa jaye, phir peeche backtrack karke doosra raasta try karo. Soch lo ek maze ya gufa hai: ek tunnel mein ghuste jao deep, jab aage rasta na bache tab last fork pe wapas aakar naya tunnel pakdo. Yahi "dive, fail, step-back" wala behaviour DFS hai.
Iska engine hota hai stack — LIFO, matlab jo node sabse last visit kiya wahi sabse pehle wapas explore hota hai. Recursion khud ek stack hota hai (call stack), isliye DFS recursive likhna sabse natural hai. Ek cheez bilkul mat bhoolna: visited array. Graph mein cycles hote hain (A→B→C→A), agar visited nahi rakhoge to program infinite loop mein ghoomta rahega. Isliye node ko visited=True mark karo ENTER karte hi — explore function ki pehli line mein.
Complexity rattna mat — derive karo. Har vertex ek baar visit hota hai → V kaam. Har vertex pe uski adjacency list scan hoti hai, sab milake total edges = 2E (undirected, Handshake Lemma) → E kaam. Total = O(V+E). E ki jagah sirf E kyun nahi? Kyunki kuch graph mein vertices hote hain par edges zero — tab bhi har vertex touch karna padta hai, isliye V term zaroori hai. Space O(V) — visited array plus stack depth.
Exam aur interview mein DFS bahut kaam aata hai: connected components count karna, cycle detect karna, topological sort (DFS post-order ulta). Bas teen cheezein yaad rakho — deep jao, visited mark karo entry pe, aur cost V+E gino edges aur nodes ko alag-alag.