Problem Solving with Go course

Stacks, Queues and SearchTracing the Path Back

Problem Solving with Go

Display

Theme

Stacks, Queues and Search · Output exercise

Tracing the Path Back

BFS tells you how far the exit is. Some puzzles also want which way: the cells on the path, the moves in order, or the path drawn on the map. For that, BFS needs to remember one more thing.

Remember where you came from

When BFS reaches a new cell, it reaches it from exactly one cell: the one it's exploring right now. Store that in a map:

from := map[Point]Point{start: start}
// ...inside the BFS loop, for a neighbour not seen yet:
from[next] = cur
queue = append(queue, next)

from replaces dist as the set of cells already seen. Each cell points one step back towards the start, so the map is a trail of arrows that all lead to S.

Walk the arrows back

From the exit, follow the arrows until you reach the start:

for p := end; p != start; p = from[p] {
	// p is on the shortest path
}

This visits the path backwards, from E to S. Counting the loop's turns gives the number of steps. If you need the path from start to end, collect the points in a slice and reverse it with slices.Reverse.

Check first that end is in from at all. If BFS never reached it, from[end] is the zero Point{0, 0}, and the loop would wander off.

When there's more than one shortest path

A grid often has several paths of the same length, and which one BFS finds depends on the order of dirs. This lesson's maze has only one shortest path, so any correct BFS draws the same picture. In a puzzle that asks about "the" path, check whether it says how ties are broken.

Task

This lesson's input is a maze with a start S and an exit E. Find the shortest path, then print the maze with every cell on the path between S and E replaced by o (S and E stay as they are), followed by the line steps: N with the number of steps from S to E. The output must match the expected output exactly.

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}}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	rows := strings.Split(strings.TrimSpace(strings.ReplaceAll(string(data), "\r\n", "\n")), "\n")
	grid := make([][]byte, len(rows))
	var start, end Point
	for r, row := range rows {
		grid[r] = []byte(row)
		for c, ch := range grid[r] {
			switch ch {
			case 'S':
				start = Point{r, c}
			case 'E':
				end = Point{r, c}
			}
		}
	}

	// TODO: BFS from start with a map[Point]Point that remembers where each cell
	// was reached from. Then walk back from end to start, count the steps and mark
	// every cell in between (not S, not E) with 'o'.
	steps := 0
	_, _ = start, end

	for _, row := range grid {
		fmt.Println(string(row))
	}
	fmt.Println("steps:", steps)
}
Go runtime not loaded yet

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