3.5.4 · HinglishGraphs

BFS — algorithm, queue-based, O(V+E), shortest path in unweighted graphs

1,827 words8 min readRead in English

3.5.4 · Coding › Graphs


BFS HAI KYA?

  • YEH kya produce karta hai: ek level-order visiting sequence, ek BFS tree, aur (unweighted graphs ke liye) source se distances shortest-path wali.
  • YEH kaun se data structures use karta hai: ek queue (the frontier) + ek visited/dist array.

Queue kyun "rings" deta hai

Agar hum stack (LIFO) use karein uski jagah, hum pehle deep dive karte — woh DFS hai, aur woh shortest paths nahi deta.


Algorithm KAISE chalta hai (first principles se derivation)

Hum chahte hain: har node ke liye, source se minimum edges ki sankhya .

Claim jis par hum build karte hain: agar hum pehle se saare nodes distance par jaante hain, toh distance par har node kisi distance- node ka neighbor hai, aur abhi tak visited nahi hai.

Steps ki derivation:

  1. Shuru: . ko queue mein daalo. (Kyun? Khud se distance 0 hai.)
  2. Ek node pop karo (queue mein sabse purana → sabse chhota distance). (Sabse purana kyun? Level order maintain karne ke liye.)
  3. ke har neighbor ke liye jo unvisited hai: woh pehli baar reach hua hai, toh . Mark visited karo, ko push karo. (Mark abhi kyun, push ke time par? Taki woh kabhi do baar queue mein na jaaye.)
  4. Repeat karo jab tak queue empty na ho jaaye.
BFS(s):
    dist[s] = 0
    visited[s] = True
    queue = [s]
    while queue not empty:
        u = queue.popleft()          # FIFO → smallest dist first
        for w in adj[u]:
            if not visited[w]:
                visited[w] = True     # mark at enqueue time!
                dist[w]    = dist[u] + 1
                parent[w]  = u        # for path reconstruction
                queue.append(w)
Figure — BFS — algorithm, queue-based, O(V+E), shortest path in unweighted graphs

Shortest path kyun? (proof sketch)


kyun hai?


Worked Examples


Common Mistakes (Steel-manned)


Recall Feynman: ek 12-saal ke bacche ko samjhao

Socho graph ek metro map hai aur tum ek station par start karte ho. Tum pehle apne home station par "0" likhte ho. Phir tum har station ko visit karte ho jo ek hop door hai aur "1" likhte ho. Phir har naya station jo unse ek hop door hai usse "2" milta hai, aur aise hi. Tum hamesha saare chhote numbers khatam karte ho kisi bhi bade number se pehle — jaise floor 1 par sabko check karna floor 2 par jaane se pehle. Jo number tumne likha woh us station tak sabse kam hops hai. "Queue" bas stations ki ek line hai apni baari ka intezaar karti — pehle line mein aaya, pehle jaata hai.


Active Recall

BFS ko kaun sa data structure drive karta hai aur kyun?
Ek FIFO queue — yeh nodes ko arrival order mein serve karta hai, level-by-level (distance-sorted) exploration guarantee karta hai.
BFS unweighted graphs mein shortest paths kyun dhundta hai?
Nodes ko non-decreasing distance order mein dequeue kiya jaata hai, toh pehli baar jab koi node reach hota hai woh fewest edges se hota hai.
BFS ki time complexity kya hai aur kyun?
— har vertex ek baar enqueued/dequeued hota hai (), har edge ek baar scan hoti hai (); alag loops hain toh hum add karte hain.
Node ko visited kab mark karna chahiye?
Enqueue (push) ke time par, taki same node queue mein multiple baar add na ho.
Weighted shortest paths ke liye BFS galat kyun hai?
BFS edge count minimize karta hai, total weight nahi; weighted (non-negative) graphs ke liye Dijkstra use karo.
Shortest path itself ko reconstruct kaise karte hain?
parent[w] store karo jab w discover karo, phir target se source tak parents walk karo aur reverse karo.
BFS ke dauran kisi bhi moment par queue mein kya hota hai?
At most do consecutive levels aur ke nodes, jisme level- nodes aage hote hain.
Shortest path ke liye DFS vs BFS — kaun sa aur kyun?
BFS; DFS stack (LIFO) use karta hai aur deep dive karta hai, toh pehla arrival guaranteed shortest nahi hota.

Connections

  • DFS — depth-first traversal (stack/recursion, cycles, components, topological order ke liye use hota hai)
  • Dijkstra's Algorithm (BFS jo weighted graphs ke liye priority queue se generalize kiya gaya)
  • 0-1 BFS (0/1 edge weights ke liye deque trick)
  • Graph Representations — adjacency list vs matrix ( mein ko affect karta hai)
  • Connected Components (har unvisited node se BFS chalao)
  • Bipartite Check (BFS 2-coloring by level parity)
  • Shortest Path Tree (parent pointers yeh tree banate hain)

Concept Map

d s = 0

uses

uses

serves oldest first

non-decreasing distance

proves

marked at enqueue

discovers w via u

records

runs in

if replaced by stack LIFO

Source node s

BFS traversal

FIFO queue

Visited set

Level-order rings

Two-level invariant

Shortest path in unweighted graph

No node queued twice

d w = d u + 1

parent for path reconstruction

O V+E time

DFS - no shortest path