Graph Algorithms & Logics (Animated): BFS/DFS Edges, Topological Sort, SCCs & Dijkstra/Bellman-Ford
Animated BFS FIFO queue vs DFS LIFO stack, DFS parenthesis theorem & Back-Edge cycle detection, Kahn vs DFS topological sort, Kosaraju SCCs, and Dijkstra vs Bellman-Ford negative weight traps.
1. Interactive BFS (FIFO Queue) vs DFS (LIFO Stack) Simulator
Toggle between BFS and DFS below to watch how a FIFO queue explores layer-by-layer (computing unweighted shortest paths!) while a LIFO stack plunges along deep paths:
BFS Queue vs DFS Stack Traversal
[S]2. DFS Edge Classification, Topological Sort & Strongly Connected Components
| Graph Type | Tree Edges | Back Edges | Forward Edges | Cross Edges |
|---|---|---|---|---|
| Directed Graph | ✅ () | ✅ (Cycle!) | ✅ | ✅ () |
| Undirected Graph | ✅ | ✅ (Cycle!) | ❌ Impossible | ❌ Impossible |
- Topological Sort (DAGs only, ): Either (1) Kahn’s Algorithm (repeatedly dequeue in-degree vertices — if vertices output, graph has a cycle!) or (2) Reverse of DFS Finishing Times (decreasing ).
- Kosaraju’s SCC Algorithm: (1) Run DFS on to record finish times ; (2) Transpose edges to form ; (3) Run DFS on in decreasing order of — each DFS tree in step 3 is one Strongly Connected Component!
3. Interactive Dijkstra Greedy Relaxation Animation
Dijkstra Shortest Path (Greedy)
[S]Dijkstra Negative-Edge Trap: Dijkstra fails on negative edge weights even when there is no negative-weight cycle! Once Dijkstra extracts vertex from the min-priority queue, it assumes is final — a later negative edge with violates this greedy invariant (and simply adding to every edge changes multi-hop path costs unequally!). Use Bellman-Ford ( full edge-relaxation passes; pass detects negative cycles!).
Practice Questions on This Chapter (1)
Let be a connected, weighted undirected graph with all edge weights strictly distinct. Which of the following statements are ALWAYS TRUE?