Module 9 · Graphs and Tries · Lesson 30 of 40
Exploring a graph: BFS and DFS
Visit every reachable vertex with a queue (BFS) or a stack/recursion (DFS), and never visit one twice.
In this lesson · about 24 minutes
- Run BFS with a queue and a visited set
- Run DFS with recursion
- Count connected parts and find shortest paths in unweighted graphs
Graph search is like tree traversal, with one big difference: graphs can have cycles, so you could go round in circles forever. The fix is a visited set: never visit a vertex twice.
BFS: breadth-first search
Explore in rings: first the start, then all its neighbours, then their neighbours, and so on. It uses a queue.
from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
v = queue.popleft()
order.append(v)
for n in graph[v]:
if n not in visited:
visited.add(n)
queue.append(n)
return order
Because BFS goes ring by ring, the first time it reaches a vertex is by the fewest edges. So BFS finds shortest paths in unweighted graphs.
DFS: depth-first search
Go as far as you can down one path, then back up and try the next. It uses a stack, or simply recursion.
def dfs(graph, v, visited):
visited.add(v)
for n in graph[v]:
if n not in visited:
dfs(graph, n, visited)
Both visit every vertex and every edge once: O(V + E).
Try it · see it work
Graph search: BFS vs DFS
Run BFS, then DFS, from the same start. BFS spreads out in rings; DFS dives deep first.
visited
—
queue (front first)
A
Step 1 of 9Put A in the queue and mark it as seen.
What else can they do?
- Connected parts: start a search from every unvisited vertex. Each new start is a new separate part ("component").
- Cycle check: in an undirected graph, if DFS finds a visited neighbour that is not the vertex it came from, there is a cycle.
- Grids: a maze or map is a graph where each cell's neighbours are up, down, left and right. "Count the islands" is connected parts on a grid.
- Multi-source BFS: put many start points in the queue at once, for example "how far is every cell from the nearest exit?"
- Bipartite check: can you colour every vertex red or blue so no edge joins two of the same colour? BFS colours as it goes.
Exercise
Fewest steps with BFS
Write steps(graph, start, goal) that returns the fewest edges from start to goal, or -1 if the goal can't be reached. Use BFS, storing each vertex's distance in a dict.
Code that runs before yours
from collections import deque
city = {
"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],
"D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"], "G": [],
}Exercise
Count the islands
A map is a grid of "1" (land) and "0" (water). Land cells touching up, down, left or right form one island. Write islands(grid) that returns how many islands there are. For each unvisited land cell, count one island and use DFS to mark its whole island as visited.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.