Graphs in practice
After this: Build a graph from a list of edges, and walk a grid as if it were a graph.
On this page · 6 sections · 3 checks
You now know two ways to walk through a graph. This lesson covers two habits that help on real problems: building the lists from whatever input you are given, and noticing when you do not need any lists at all.
Building the lists from the edges alone
In the lesson on storing a graph, we knew all the nodes before we started. Problems often give you only the edges. So you create each node's list the first time that node appears.
Suppose the edges are A–B and A–C.
- The first edge is A–B. Neither A nor B has a list yet, so create both. Add B to A's list and A to B's list.
- The second edge is A–C. A already has a list, so add C to it. C has no list yet, so create one and add A to it.
Here is the code for the six-node graph, using the edges list from that earlier lesson.
from collections import defaultdict
adj = defaultdict(list) # a missing key starts as an empty listfor a, b in edges: adj[a].append(b) adj[b].append(a)
print(len(adj), adj["F"])6 ['E']
Map<String, List<String>> adj = new HashMap<>();for (String[] e : edges) { adj.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]); // a missing key starts as an empty list adj.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]);}
System.out.println(adj.size() + " " + adj.get("F"));6 [E]
A defaultdictcomputeIfAbsent creates the missing list for you, so the loop stays short. The result has 6 keys, and F's list holds E.
A grid is a graph you never build
Think of a maze, a game board or an image. Each is a grid of cells, and we name a cell by its row and column: (r, c). Rows and columns are numbered from 0, so (0, 0) is the top-left cell.
A grid is a graph. The cells are the nodes, and two cells that share a side are neighbours. In a 3 × 3 grid:
- The middle cell (1, 1) has four neighbours: (0, 1), (2, 1), (1, 0) and (1, 2).
- The corner cell (0, 0) has two neighbours: (1, 0) and (0, 1). The other two would be off the grid.
If a cell is a wall, it does not count as a neighbour either.
You do not need an adjacency list for this, because the neighbours can be worked out from r and c whenever you need them. To find the fewest moves between two cells, you use breadth-first search as before. Here is a maze with 3 rows and 4 columns, where # is a wall.
from collections import deque
def neighbours(maze, r, c): # the edges, worked out when needed for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < len(maze) and 0 <= nc < len(maze[0]) and maze[nr][nc] != "#": yield nr, nc
def shortest(maze, start, goal): dist = {start: 0} # also works as the visited set queue = deque([start]) while queue: cell = queue.popleft() if cell == goal: return dist[cell] for nb in neighbours(maze, *cell): if nb not in dist: dist[nb] = dist[cell] + 1 queue.append(nb) return -1 # no path
maze = ["....", ".##.", ".#.."]print(shortest(maze, (0, 0), (2, 2)))6
static int shortest(String[] maze, int sr, int sc, int gr, int gc) { int rows = maze.length, cols = maze[0].length(); int[][] dist = new int[rows][cols]; // -1: not seen yet; also works as the visited set for (int[] row : dist) Arrays.fill(row, -1); dist[sr][sc] = 0; Deque<int[]> queue = new ArrayDeque<>(); queue.add(new int[] {sr, sc}); int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (!queue.isEmpty()) { int[] cell = queue.poll(); int r = cell[0], c = cell[1]; if (r == gr && c == gc) return dist[r][c]; for (int[] m : moves) { // the edges, worked out when needed int nr = r + m[0], nc = c + m[1]; if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue; if (maze[nr].charAt(nc) == '#' || dist[nr][nc] != -1) continue; dist[nr][nc] = dist[r][c] + 1; queue.add(new int[] {nr, nc}); } } return -1; // no path}6
- The four pairs in neighbourspairs in moves are the moves: down, up, right and left. The code keeps a new cell only if it is on the grid and is not a wall.
- The Python version uses
yield, which hands back one cell at a time to the loop that asked for it. shortestis breadth-first search, using cells instead of letters. It stops as soon as it reaches the goal.distalso does the job of the visited set: a cell has a distance if it has been seen.
In this tool, node 00 is the cell at row 0, column 0, node 01 is row 0, column 1, and so on.
- BFS from 00Run breadth-first search from the top-left cell, 00. Each number is the fewest moves from 00. The walls force the walk to go round the top, so cell 22 ends at 6.
Pick a start node and run an algorithm.
Counting islands with flood fill
A grid can also hold land (1) and water (0). An island is a group of land cells joined by shared sides. Depth-first search can count them.
When you find a land cell, you have found a new island. Turn it and all the land joined to it into water, so that you cannot count that island twice. This is called . Paint programs use the same idea to fill a shape. Take this grid.
1 1 00 1 00 0 1- Scan from the top left. (0, 0) is land, so the count becomes 1. The fill turns (0, 0), (0, 1) and (1, 1) into water.
- Carry on scanning. The next land cell is (2, 2), so the count becomes 2. The fill turns it into water.
- No land is left, so the answer is 2.
(1, 1) and (2, 2) touch only at a corner, so they are not neighbours.
def num_islands(grid): rows, cols = len(grid), len(grid[0])
def sink(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1": return # off the grid, water, or already sunk grid[r][c] = "0" # mark visited by sinking the land sink(r + 1, c) sink(r - 1, c) sink(r, c + 1) sink(r, c - 1)
count = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1": count += 1 # unsunk land: a new island sink(r, c) # sink all of it before moving on return count
grid = [list("110"), list("010"), list("001")]print(num_islands(grid))2
static int numIslands(char[][] grid) { int count = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { if (grid[r][c] == '1') { count++; // unsunk land: a new island sink(grid, r, c); // sink all of it before moving on } } } return count;}
static void sink(char[][] grid, int r, int c) { if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return; // off the grid, water, or already sunk grid[r][c] = '0'; // mark visited by sinking the land sink(grid, r + 1, c); sink(grid, r - 1, c); sink(grid, r, c + 1); sink(grid, r, c - 1);}2
sinkis depth-first search on the grid. It stops if the cell is off the grid or is not land.- Otherwise it turns the cell into water and calls itself on the four neighbours. The grid itself records what has been visited, so no separate set is needed.
- The two loops scan every cell. Each land cell they find is a new island, because
sinkhas removed the earlier islands.
Which walk should you use?
| You want | Use | Why |
|---|---|---|
| The fewest edges, the nearest match, or layers | BFS | it visits nodes in order of distance |
| To know if a path exists, or which nodes are connected | either | both reach everything that can be reached |
| To count regions or fill a region | DFS or BFS | recursion makes DFS short to write |
| To find a cycle in an undirected graph | DFS | the walk knows each node's parent |
With an adjacency list, both cost O(nodes + edges): the work grows with the number of nodes plus the number of edges.
Check yourself
In a grid where you can move up, down, left and right, what are the neighbours of cell (r, c)?
You need the fewest moves from one cell of a grid to another. Should you use BFS or DFS, and why?
The maze has 3 rows and 4 columns, and # is a wall. What does the last line print?
from collections import deque
def neighbours(maze, r, c): # the edges, worked out when needed for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < len(maze) and 0 <= nc < len(maze[0]) and maze[nr][nc] != "#": yield nr, nc
def shortest(maze, start, goal): dist = {start: 0} # also works as the visited set queue = deque([start]) while queue: cell = queue.popleft() if cell == goal: return dist[cell] for nb in neighbours(maze, *cell): if nb not in dist: dist[nb] = dist[cell] + 1 queue.append(nb) return -1 # no path
maze = ["....", ".##.", ".#.."]print(shortest(maze, (0, 0), (2, 2)))static int shortest(String[] maze, int sr, int sc, int gr, int gc) { int rows = maze.length, cols = maze[0].length(); int[][] dist = new int[rows][cols]; // -1: not seen yet; also works as the visited set for (int[] row : dist) Arrays.fill(row, -1); dist[sr][sc] = 0; Deque<int[]> queue = new ArrayDeque<>(); queue.add(new int[] {sr, sc}); int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (!queue.isEmpty()) { int[] cell = queue.poll(); int r = cell[0], c = cell[1]; if (r == gr && c == gc) return dist[r][c]; for (int[] m : moves) { // the edges, worked out when needed int nr = r + m[0], nc = c + m[1]; if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue; if (maze[nr].charAt(nc) == '#' || dist[nr][nc] != -1) continue; dist[nr][nc] = dist[r][c] + 1; queue.add(new int[] {nr, nc}); } } return -1; // no path}Connect
- Build an adjacency list from a list of edges, with defaultdict in Python or computeIfAbsent in Java.
- Treat a grid as a graph: each cell is a node, and its four neighbours are worked out when needed, not stored.
- Choose breadth-first search for the fewest moves, and depth-first search to explore what can be reached.