Graphs · Exercise 55 of 100

Breadth-first search on a matrix

Treat each open cell as a vertex and each allowed move to a neighboring open cell as an edge. If moves have equal cost, use a queue and mark cells when adding them so each cell enters once. Each new layer of the search is one move farther from the start.

Try it yourself

A maze has three rows, 'S#.T', '.#..' and '....', from top to bottom. A dot is open and # is a wall. If each move goes one cell up, down, left or right, at what distance from S does BFS first reach T?

One-step hint

Copy the maze and write zero at S. Number open neighbors in waves, increasing the distance once per wave and leaving walls untouched.

Worked solution
  1. From S the first two layers go down the first column. The next two go right along the bottom row, reaching its third cell at distance 4.
  2. Layer 5 reaches the middle cell of column 3 and the bottom cell of column 4. Layer 6 reaches the cells just left of and just below T, so T first enters layer 7.
DSA compiler