Graph Patterns
BFS, DFS, topological sort, union-find, Dijkstra and Bellman-Ford.
8 pages
- Pattern 16: Graph Patterns (BFS / DFS / Topological Sort / Union-Find / Dijkstra)Pattern guide
Graphs have six algorithm templates (all spelled out in §3 below) but only one setup step — and that setup is where most interview time is actually lost…
- LC 200Number of Islands (LC 200)Medium
Iterate every cell. When you hit unvisited '1', run DFS/BFS to "sink" all connected '1's into '0's and increment a counter.
- LC 207Course Schedule (LC 207)Medium
A directed graph has a valid order iff it has no cycle. Kahn's algorithm processes nodes whose in-degree is 0; if all nodes get processed, the graph is…
- LC 547Number of Provinces (LC 547)Medium
Count connected components in an undirected graph given as an adjacency matrix. Each "province" is one component.
- LC 743Network Delay Time (LC 743)Medium
Find the shortest delay from source k to every other node. The "delay" of the whole network is the maximum shortest delay among all reachable nodes. If any…
- LC 684Redundant Connection (LC 684)Medium
Add edges one by one. The first edge whose two endpoints are already in the same Union-Find component is the redundant one.
- LC 994Rotting Oranges (LC 994)Medium
All initially rotten oranges spread their rot at the same time. Push every rotten cell into the BFS queue at once, then do level-order BFS — each level = 1…
- LC 210Course Schedule II (LC 210)Medium
Same as LC 207, but instead of just true/false, return one valid topological ordering. If a cycle exists, return an empty array.