Graphs: BFS and DFS
A graph is a set of nodes (vertices) connected by edges. It's the most general data structure: road maps, social networks, the web's links, package dependencies, airline routes, and even game states are graphs. Trees are just graphs without cycles. The two fundamental ways to explore a graph are breadth-first search (BFS) and depth-first search (DFS).
Kinds of graphs
| Example | |
|---|---|
| Undirected: edges go both ways | Friendships, roads |
| Directed: edges have a direction | "Follows" on social media, task dependencies, links |
| Weighted: edges have costs | Distances, prices, latencies |
| Cyclic / acyclic | A directed acyclic graph (DAG) has no cycles: build steps, course prerequisites |
Representing a graph
The usual choice is an adjacency list: each node maps to its neighbours. It uses O(V + E) memory, where V is the number of vertices and E the number of edges.
An adjacency matrix (matrix[a][b] = 1) answers "are a and b connected?" in O(1), but needs O(V²) memory, so it suits small, dense graphs.
Breadth-first search
BFS explores in rings: all neighbours first, then their neighbours, and so on, using a queue. Because it reaches nodes in order of distance, BFS finds the shortest path in an unweighted graph:
Each node and edge is processed once: O(V + E).
Depth-first search
DFS goes as deep as possible before backtracking, using recursion (or an explicit stack). It's the natural tool for exploring every reachable node, finding connected components, detecting cycles and ordering dependencies:
| BFS | DFS | |
|---|---|---|
| Uses | A queue | A stack (or recursion) |
| Explores | Level by level | One path to the end, then backtracks |
| Shortest path (unweighted) | ✔ | ✖ |
| Typical uses | Shortest paths, nearest X, levels | Components, cycles, topological order, mazes, backtracking |
| Time | O(V + E) | O(V + E) |
Grids are graphs
Each cell is a node connected to its up/down/left/right neighbours. Counting islands (connected groups of land cells) is one of the most common interview questions:
And BFS on a grid finds the shortest route through a maze:
Cycle detection in a directed graph
In a dependency graph, a cycle means "A needs B needs C needs A": impossible to build. DFS with three colours finds it: white (unvisited), grey (on the current path), black (finished). Reaching a grey node means you've looped back:
Practice
- Is there a path between two nodes? Write it with BFS and with DFS.
- "Rotting oranges": in a grid, each minute rotten oranges spoil their neighbours. How many minutes until all are rotten? (Hint: BFS from all rotten oranges at once.)
- Clone a graph: return a deep copy of every node and edge.
1.Which search finds the shortest path in an unweighted graph?
2.What is the time complexity of BFS or DFS on an adjacency list?
3.In three-colour DFS cycle detection, what does reaching a grey node mean?