BFS: the Shortest Path on a Grid
"What's the fewest steps from S to E?" is one of the most common puzzle questions. When every step costs the same, the answer is breadth-first search (BFS): explore outwards in rings, nearest cells first.
Rings around the start
BFS keeps a queue of cells still to explore. It starts with the start cell at distance 0. Then, over and over: take the front cell, look at its neighbours, and give every neighbour not seen yet the distance of the current cell plus 1, adding it to the back of the queue.
######### #########
#S...#..# #0123#..#
#.##.#..# → #1##4#..#
#...#...# #234#...#
######### #########
Because the queue is first in, first out, all cells at distance 1 are explored before any at distance 2, and so on. So the first time BFS reaches a cell, it has found the shortest way there. Never update a distance once it's set.
The code
dist := map[Point]int{start: 0}
queue := []Point{start}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
for _, d := range dirs {
next := Point{cur.Row + d.Row, cur.Col + d.Col}
if _, seen := dist[next]; seen || !open(grid, next) {
continue
}
dist[next] = dist[cur] + 1
queue = append(queue, next)
}
}
The dist map does two jobs: it stores the answer, and it is the set of cells already seen, so no cell enters the queue twice. Mark a cell as seen when you add it to the queue, not when you take it out, or the same cell can be queued many times.
When the search ends, dist holds every reachable cell. A cell that isn't in the map can't be reached at all.
Task
This lesson's input is a maze: # is a wall, everything else is open, S is the start and E the exit. Point, dirs, open and find are ready.
- Complete
bfs(grid []string, start Point) map[Point]int: the fewest steps fromstartto every open cell it can reach, moving up, down, left or right. - Complete
shortest(grid []string) int: the fewest steps fromStoE, or-1whenEcan't be reached or either letter is missing.