DSA Master › Topic 13
Graphs
Model the problem as nodes and edges first, then pick an algorithm. Use BFS for shortest paths when edges are unweighted, DFS or Union-Find for connectivity, topological sort for dependencies, Dijkstra for weighted shortest paths, and Prim's or Kruskal's for the minimum cost to connect everything.
Concepts
- Adjacency list & matrix
- BFS & DFS
- Cycle detection
- Topological sort (Kahn's & DFS)
- Union Find / DSU
- Dijkstra
- MST – Prim's & Kruskal's
How to recognise it
- A grid of cells (islands, oranges, water flow) is a graph where each cell links to its neighbours.
- "Prerequisites" or "order of tasks" means a directed graph that needs a topological sort.
- "Is it connected?", "redundant edge" or "number of components" points to Union-Find.
- Weighted edges with a cheapest path or minimum cost point to Dijkstra or MST.
Common pitfalls
- In BFS, mark a node visited when you enqueue it, not when you dequeue it.
- Multi-source BFS (Rotting Oranges): put every source in the queue before you start.
Problems
- Number of Islands (Medium)
- Max Area of Island (Medium)
- Clone Graph (Medium)
- Rotting Oranges (Medium)
- Course Schedule (Medium)
- Course Schedule II (Medium)
- Pacific Atlantic Water Flow (Medium)
- Graph Valid Tree (Medium, Premium)
- Number of Connected Components in an Undirected Graph (Medium, Premium)
- Redundant Connection (Medium)
- Network Delay Time (Medium)
- Cheapest Flights Within K Stops (Medium)
- Min Cost to Connect All Points (Medium)