Graphs: BFS, DFS, topological sort, Dijkstra
Model problems as graphs and pick the right traversal.
By Invicly Tech, , in Interview Preparation. About 14 minutes to read.
In short
A graph is nodes connected by edges, stored as an adjacency list. BFS finds fewest-edge paths, DFS explores components, topological sort orders dependencies and Dijkstra handles weighted shortest paths.
Explained simply
A graph is a set of things (called nodes or vertices) and the links between them (called edges). Cities and roads, people and friendships, web pages and links, courses and their prerequisites: all of these are graphs. Edges can be one-way (directed) or two-way (undirected), and they can carry a cost such as distance or time (weighted).
Many interview problems are graphs in disguise. A grid of land and water is a graph where each cell links to its four neighbours. A list of "take course A before course B" rules is a directed graph. Spotting the graph is often the hardest step.
Once you see the graph, you choose how to walk it. Breadth-first search (BFS) spreads out in rings, like ripples in water, so it finds the fewest steps. Depth-first search (DFS) follows one path as far as it can, which is good for exploring whole regions and finding cycles.
Two more tools cover most of the rest. Topological sort puts tasks in an order that respects every dependency. Dijkstra's algorithm finds the cheapest path when edges have costs. All of them need a seen set, so you never visit the same node twice.
Press Play on a diagram to walk through it one step at a time.
- 1Queue the start
Mark it seen with distance 0
- 2Pop the front
Process nodes in order of distance
- 3Visit neighbours
Skip any already seen
- 4Mark and enqueue
Mark when enqueued to avoid duplicates
- 5Repeat until empty
O(V + E) total
- Queue
- Fewest edges, unweighted
- Grids, word ladders
- O(V + E)
- Stack or recursion
- Components, cycles, ordering
- Islands, Course Schedule
- O(V + E)
- Min-heap of distances
- Weighted, non-negative edges
- Network Delay Time
- O(E log V)
- 1Start
A = 0, all others infinity
- 2Pop A (0)
B = 4, C = 1
- 3Pop C (1)
B improves to 3, D = 6
- 4Pop B (3)
D improves to 4
- 5Pop D (4)
Old entries B 4 and D 6 are skipped
- 6Done
A 0, C 1, B 3, D 4
In depth
Turning the input into a graph
Inputs usually arrive as an edge list like [[0, 1], [1, 2]]. Convert it to an adjacency list: for each node, a list of its neighbours. For an undirected edge, add it both ways; for a directed edge, add it only from source to target. An adjacency list uses O(V + E) memory, where V is the number of nodes and E the number of edges.
An adjacency matrix (a V x V table of true or false) answers "is there an edge from a to b?" in O(1), but it costs O(V^2) memory, which is too much for 100,000 nodes. Grids need no conversion at all: the neighbours of (r, c) are (r + 1, c), (r - 1, c), (r, c + 1) and (r, c - 1), as long as they are inside the grid.
- Undirected: add the edge both ways
- Directed: only from source to target
- Grid: use a directions array and check bounds first
- Matrix only for small, dense graphs
Grids: islands and multi-source BFS
Number of Islands is the classic grid problem. Scan every cell. When you find unvisited land, count one island and flood-fill it: visit all connected land with DFS or BFS and mark it, often by changing 1 to 0 in place. Each cell is handled a constant number of times, so the total is O(m x n).
Recursive DFS on a 1000 x 1000 grid of land can go a million calls deep and overflow the stack, so BFS or an explicit stack is safer for big inputs. When several starting points spread at the same time, like rotting oranges or distance to the nearest exit, put all of them in the queue at distance 0 before you start. This multi-source BFS finds every cell's distance to its nearest source in a single pass.
Cycles and ordering with DFS colours
Kahn's algorithm (removing nodes with no incoming edges) is one way to do topological sort. The DFS way uses three colours. White means not visited yet. Gray means the node is on the current DFS path. Black means the node and everything below it are finished.
While exploring a directed graph, an edge into a gray node means you have looped back onto your own path: that is a cycle. An edge into a black node is fine; that part was already checked. If you record each node when it turns black, the reversed list is a valid topological order. For an undirected graph the rule is simpler: seeing a visited node that is not the parent you came from means a cycle.
- 1White
Not visited yet
- 2Enter: gray
Node is on the current path
- 3Edge to gray?
Back edge: a cycle exists
- 4Explore children
Skip black nodes, they are done
- 5Exit: black
Add to the order; reverse it at the end
How Dijkstra really works
Dijkstra keeps the best known distance to every node, starting with 0 for the source and infinity for the rest. A min-heap holds (distance, node) pairs. Each round, pop the closest node. Because every edge weight is zero or more, nothing found later can make that node cheaper, so its distance is now final. Then relax its edges: if going through it gives a neighbour a shorter distance, update it and push the new pair.
The heap can hold old, larger entries for the same node. When you pop one whose distance is bigger than the best known, skip it. This lazy approach costs O(E log V). With a negative edge, a node popped as final could later get cheaper, so use Bellman-Ford instead, which costs O(V x E).
- Final when popped, only if weights are non-negative
- Skip stale heap entries
- Negative weights: Bellman-Ford
- All pairs on a small graph: Floyd-Warshall, O(V^3)
Picking the algorithm from the question
Read the question for clues. "Fewest moves" or "shortest" with no costs means BFS. Costs that are all non-negative mean Dijkstra. If every cost is 0 or 1, a 0-1 BFS with a deque (push 0-cost moves to the front, 1-cost moves to the back) runs in O(V + E). "Can all tasks be finished" or "in what order" means topological sort. "How many groups" or "are these connected" means DFS, BFS or union-find. A limit on the number of stops, as in Cheapest Flights Within K Stops, suits a Bellman-Ford variant that runs only k + 1 rounds.
- Fewest steps
- No weights: BFS
- Weights 0 or 1: 0-1 BFS
- Cheapest path
- Non-negative: Dijkstra
- Negative or k stops: Bellman-Ford
- Order of tasks
- Topological sort
- Leftover nodes mean a cycle
- Groups or connected?
- DFS or BFS flood fill
- Union-find if edges arrive over time
Learn it in 6 short steps
About 1h 30m each. Track them with a timer in your plan.
- 1Represent graphs with adjacency lists~1h 30m
- 2Traverse grids and graphs with BFS and DFS~1h 30m
- 3Detect cycles and order with topological sort~1h 30m
- 4Find shortest paths with Dijkstra~1h 30m
- 5Practice: Number of Islands, Course Schedule~1h 30m
- 6Practice: Network Delay Time~1h 30m
Key points
- Build an adjacency list first; a grid is a graph whose neighbours are up, down, left, right.
- BFS and DFS both run in O(V + E) time with a seen set.
- Kahn's topological sort repeatedly takes nodes with in-degree 0; leftovers mean a cycle.
- Dijkstra needs non-negative weights and runs in O(E log V) with a heap.
Key terms
Tap a card to flip it. 0/5 known
Examples
from collections import deque
def bfs(graph, start):
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist:
dist[nxt] = dist[node] + 1
queue.append(nxt)
return dist # fewest edges from start to each nodeCourse Schedule: can all courses be finished?
numCourses = 4, prerequisites [[1, 0], [2, 1], [3, 1], [3, 2]], where [a, b] means take b before a. Build edges 0 to 1, 1 to 2, 1 to 3, 2 to 3, and count incoming edges: course 0 has none, so it starts in the queue. Take 0: course 1 drops to 0 incoming, add it. Take 1: course 2 drops to 0, course 3 drops to 1. Take 2: course 3 drops to 0. Take 3. All 4 were taken, so the answer is true. Add the rule [1, 3] and courses 1, 2 and 3 never reach zero, so only 1 course is taken: false.
boolean canFinish(int n, int[][] prereq) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] p : prereq) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
Deque<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) queue.offer(i);
int taken = 0;
while (!queue.isEmpty()) {
int c = queue.poll(); taken++;
for (int next : adj.get(c)) if (--indeg[next] == 0) queue.offer(next);
}
return taken == n; // fewer means a cycle blocked some courses
}Network Delay Time with Dijkstra
times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, source k = 2. Each entry is (from, to, time). Pop node 2 at time 0 and push 1 and 3 at time 1. Pop 1 (time 1, no edges out). Pop 3 (time 1) and push 4 at time 2. Pop 4 at time 2. Every node was reached, and the signal reaches the last one at time 2, so the answer is 2. If some node were never reached, the answer would be -1.
import heapq
from collections import defaultdict
def network_delay_time(times, n, k):
adj = defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
dist, heap = {}, [(0, k)]
while heap:
d, u = heapq.heappop(heap)
if u in dist:
continue # already final with a smaller time
dist[u] = d
for v, w in adj[u]:
if v not in dist: heapq.heappush(heap, (d + w, v))
return max(dist.values()) if len(dist) == n else -1 # O(E log V)Quick reference
- Undirected edge u-v: add v to adj[u] and u to adj[v]
- Mark a node seen when you push it, not when you pop it, so it is queued only once
- Multi-source BFS: put every source in the queue at distance 0 before starting
- Directed cycle check: an edge into a gray node (on the current path) means a cycle
- Dijkstra: skip any popped entry whose distance is larger than the best known
- Negative weights: Bellman-Ford in O(V x E); at most k stops: run k + 1 rounds
- Deep recursive DFS on big grids can overflow the stack; use BFS or an explicit stack
- Weights only 0 or 1: 0-1 BFS with a deque runs in O(V + E)
Common mistakes
- Marking nodes seen when popped instead of when pushed, adding duplicates.
- Using BFS for weighted shortest paths.
- Forgetting disconnected parts: loop over every node as a possible start.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Find if Path Exists in Graph: given n nodes, an undirected edge list, a source and a destination, return true if the destination is reachable.
- Exercise 2medium
Rotting Oranges: each minute, rotten oranges (2) rot their fresh neighbours (1). Return the minutes until no fresh orange is left, or -1 if that never happens.
- Exercise 3hard
Cheapest Flights Within K Stops: find the cheapest price from src to dst using at most k stops, or -1.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use BFS or DFS?
- Use BFS when you need the fewest steps or want to work level by level. Use DFS for exploring whole regions, detecting cycles or building a topological order. For simply visiting everything, either works.
- When do I need Dijkstra instead of BFS?
- When edges have different non-negative costs. BFS counts edges, not total cost, so it can pick a path with fewer but more expensive edges.
- How do I spot a graph problem when the word graph never appears?
- Look for things linked to other things: grid cells with neighbours, tasks with dependencies, words that change one letter at a time, or states you can move between. Each thing is a node and each allowed move is an edge.
- Do I need to know A*, Floyd-Warshall or minimum spanning trees?
- They come up less often. Know that Floyd-Warshall finds all-pairs shortest paths in O(V^3) for small graphs, and that Kruskal's minimum spanning tree uses sorting plus union-find; A* is rare outside game and map roles.