23. Graphs
BFS/DFS, islands, cycles, topo sort, bipartite, shortest paths, MST, DSU, SCC and bridges.
Understand the topic
A graph is nodes connected by edges, like cities and roads. Store it as an adjacency list (List<List<Integer>>), or treat a grid as a graph where each cell connects to its four neighbours. Always keep a visited array.
Pick the tool by the question. To explore or count components, use BFS or DFS. For the shortest path with equal edges, use BFS. For an order with prerequisites, use topological sort (Kahn's algorithm). For shortest paths with weights, use Dijkstra, or Bellman-Ford when there's a limit on edges. For all pairs, use Floyd-Warshall. To connect everything cheaply, use an MST (Prim or Kruskal). For "are these connected?" while adding edges, use Union-Find. For edges whose removal disconnects the graph, use Tarjan's bridges.
| # | Problem | Pattern | Level | ||
|---|---|---|---|---|---|
| 1 | Find if Path Exists in Graph #1971 | Adjacency list + BFS | Easy | LeetCode ↗ | |
| 2 | Flood Fill #733 | Grid DFS | Easy | LeetCode ↗ | |
| 3 | Number of Islands #200 | Connected components on a grid | Medium | LeetCode ↗ | |
| 4 | Number of Provinces #547 | Connected components (adjacency matrix) | Medium | LeetCode ↗ | |
| 5 | Max Area of Island #695 | DFS returning size | Medium | LeetCode ↗ | |
| 6 | Rotting Oranges #994 | Multi-source BFS | Medium | LeetCode ↗ | |
| 7 | Pacific Atlantic Water Flow #417 | Reverse BFS/DFS from the oceans | Medium | LeetCode ↗ | |
| 8 | Clone Graph #133 | DFS with old → new map | Medium | LeetCode ↗ | |
| 9 | Course Schedule #207 | Cycle detection with Kahn's algorithm | Medium | LeetCode ↗ | |
| 10 | Course Schedule II #210 | Topological sort (Kahn) | Medium | LeetCode ↗ | |
| 11 | Is Graph Bipartite? #785 | 2-colouring with BFS | Medium | LeetCode ↗ | |
| 12 | Network Delay Time #743 | Dijkstra | Medium | LeetCode ↗ | |
| 13 | Path With Minimum Effort #1631 | Dijkstra on a grid (minimax) | Medium | LeetCode ↗ | |
| 14 | Cheapest Flights Within K Stops #787 | Bellman-Ford with k+1 rounds | Medium | LeetCode ↗ | |
| 15 | Find the City With the Smallest Number of Neighbors at a Threshold Distance #1334 | Floyd-Warshall | Medium | LeetCode ↗ | |
| 16 | Min Cost to Connect All Points #1584 | Prim's MST (dense graph) | Medium | LeetCode ↗ | |
| 17 | Redundant Connection #684 | Union-Find | Medium | LeetCode ↗ | |
| 18 | Accounts Merge #721 | Union-Find on emails | Medium | LeetCode ↗ | |
| 19 | Word Ladder #127 | BFS on implicit graph | Hard | LeetCode ↗ | |
| 20 | Critical Connections in a Network #1192 | Tarjan's bridges | Hard | LeetCode ↗ | |
| 21 | Swim in Rising Water #778 | Dijkstra (minimax) on a grid | Hard | LeetCode ↗ |
Nothing matches that filter.
Work top to bottom — each list goes from easy to hard. Try a problem for at least 15 minutes before opening a hint. Ticks are saved in your browser.