Problem Solving with Go course

Stacks, Queues and SearchBFS: the Shortest Path on a Grid

Problem Solving with Go

Display

Theme

Stacks, Queues and Search · Test exercise

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.

  1. Complete bfs(grid []string, start Point) map[Point]int: the fewest steps from start to every open cell it can reach, moving up, down, left or right.
  2. Complete shortest(grid []string) int: the fewest steps from S to E, or -1 when E can't be reached or either letter is missing.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// Point is a cell: Row grows downwards, Col grows to the right.
type Point struct {
	Row, Col int
}

// Up, down, left, right.
var dirs = []Point{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// open reports whether p is inside the grid and not a wall '#'.
func open(grid []string, p Point) bool {
	return p.Row >= 0 && p.Row < len(grid) && p.Col >= 0 && p.Col < len(grid[p.Row]) &&
		grid[p.Row][p.Col] != '#'
}

// find returns the position of the first ch in the grid.
func find(grid []string, ch byte) (Point, bool) {
	for r, row := range grid {
		if c := strings.IndexByte(row, ch); c >= 0 {
			return Point{r, c}, true
		}
	}
	return Point{}, false
}

// bfs returns the fewest steps from start to every open cell it can reach,
// moving up, down, left or right. start itself is at distance 0.
func bfs(grid []string, start Point) map[Point]int {
	// TODO: a queue of points and a map of distances, starting with start at 0
	return nil
}

// shortest returns the fewest steps from S to E, or -1 when E can't be reached
// or either of them is missing.
func shortest(grid []string) int {
	// TODO: find S and E, then look E up in bfs from S
	return -1
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	grid := strings.Split(strings.TrimSpace(strings.ReplaceAll(string(data), "\r\n", "\n")), "\n")
	start, _ := find(grid, 'S')
	fmt.Println("cells reachable from S:", len(bfs(grid, start)))
	fmt.Println("fewest steps from S to E:", shortest(grid))
}
Go runtime not loaded yet

8 lines · 88 B of the 1 MB limit. Submit always uses the lesson's own input.