# Graph Algorithms & Logics (Animated): BFS/DFS Edges, Topological Sort, SCCs & Dijkstra/Bellman-Ford
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Algorithms
Canonical URL: https://gateandnet.com/exams/gate-cs/algorithms/graph-traversals-scc-topological-and-shortest-paths-animated

> 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:

```visualizer
bfs-dfs
```

## 2. DFS Edge Classification, Topological Sort & Strongly Connected Components

| Graph Type | Tree Edges | Back Edges | Forward Edges | Cross Edges |
| :--- | :---: | :---: | :---: | :---: |
| **Directed Graph** | ✅ ($d[u]<d[v]<f[v]<f[u]$) | ✅ (Cycle!) | ✅ | ✅ ($d[v]<f[v]<d[u]<f[u]$) |
| **Undirected Graph** | ✅ | ✅ (Cycle!) | ❌ **Impossible** | ❌ **Impossible** |

- **Topological Sort (DAGs only, $\Theta(V+E)$):** Either (1) **Kahn’s Algorithm** (repeatedly dequeue in-degree $0$ vertices — if $< |V|$ vertices output, graph has a cycle!) or (2) **Reverse of DFS Finishing Times** (decreasing $f[u]$).
- **Kosaraju’s $\Theta(V+E)$ SCC Algorithm:** (1) Run DFS on $G$ to record finish times $f[u]$; (2) Transpose edges to form $G^T$; (3) Run DFS on $G^T$ in **decreasing order of $f[u]$** — each DFS tree in step 3 is one **Strongly Connected Component**!

## 3. Interactive Dijkstra Greedy Relaxation Animation

```visualizer
dijkstra
```

> [!TRAP]
> **Dijkstra Negative-Edge Trap:** Dijkstra fails on **negative edge weights** even when there is *no negative-weight cycle*! Once Dijkstra extracts vertex $u$ from the min-priority queue, it assumes $d[u]$ is final — a later negative edge $(w \to u)$ with $w < 0$ violates this greedy invariant (and simply adding $+C$ to every edge changes multi-hop path costs unequally!). Use **Bellman-Ford** ($|V|-1$ full edge-relaxation passes; pass $|V|$ detects negative cycles!).

## Solved Practice Questions & PYQs

### [GATE CS 2024 MSQ | MSQ]
Let $G = (V, E)$ be a connected, weighted undirected graph with **all edge weights strictly distinct**. Which of the following statements are **ALWAYS TRUE**?
**Correct Answer:** A,B
**Solution:** - **A & B (True):** Distinct edge weights guarantee a **unique MST**, and the lightest edge across the cut $(\{u\}, V\setminus\{u\})$ must be in the MST.
- **C (False):** If the heaviest edge is a **bridge** (cut-edge), it *must* belong to the MST!
- **D (False):** Counterexample triangle $(s,a)=2, (s,b)=2, (a,b)=1.5$: Dijkstra picks $(s,a),(s,b)$ (total $4$), Prim picks $(s,a),(a,b)$ (total $3.5$).
