Problem Solving with Go course

GraphsTracing the Route

Problem Solving with Go

Display

Theme

Graphs · Output exercise

Tracing the Route

Dijkstra gives the cost of the best route. To show the route itself, use the same trick as with BFS: remember where each node was reached from.

One more map

Whenever Dijkstra finds a cheaper way to a node, it records both the new cost and the node it came from:

if old, seen := best[e.To]; !seen || m < old {
	best[e.To] = m
	from[e.To] = cur.place
	heap.Push(q, visit{e.To, m})
}

A node can be improved several times before it's settled, and each time from is overwritten. That's what you want: when the search ends, from holds the last improvement, which belongs to the best route.

Walking back and turning around

Follow from from the goal to the start, collecting the nodes, then reverse the slice:

route := []string{goal}
for p := goal; p != start; p = from[p] {
	route = append(route, from[p])
}
slices.Reverse(route)

Reversing by hand is a short loop too: swap the first and last, then move both indexes inwards until they meet.

As with BFS, check first that the goal was reached at all. If it wasn't, from[goal] is the empty string and the loop never finds the start.

Ties

When two routes cost exactly the same, which one Dijkstra keeps depends on the order of the edges and of the heap. This lesson's map has a single best route, so every correct program prints the same answer. Puzzles that care about ties say how to break them.

Task

This lesson's input starts with a line route <from> <to>, followed by roads with their minutes. Roads go both ways. The queue type and the parsing are ready.

Print the best route as the places joined by ->, then a line with the total, such as 22 minutes. The output must match the expected output exactly.

main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// Edge is a road to another place and how many minutes it takes.
type Edge struct {
	To      string
	Minutes int
}

// visit is a place and the minutes it took to get there.
type visit struct {
	place   string
	minutes int
}

// queue is a priority queue of visits for container/heap: Pop gives the fewest minutes.
type queue []visit

func (q queue) Len() int           { return len(q) }
func (q queue) Less(i, j int) bool { return q[i].minutes < q[j].minutes }
func (q queue) Swap(i, j int)      { q[i], q[j] = q[j], q[i] }
func (q *queue) Push(x any)        { *q = append(*q, x.(visit)) }
func (q *queue) Pop() any {
	old := *q
	v := old[len(old)-1]
	*q = old[:len(old)-1]
	return v
}

func main() {
	g := map[string][]Edge{}
	var start, goal string
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) != 3 {
			continue
		}
		if f[0] == "route" {
			start, goal = f[1], f[2]
			continue
		}
		minutes, err := strconv.Atoi(f[2])
		if err != nil {
			fmt.Println("bad road:", scanner.Text())
			return
		}
		g[f[0]] = append(g[f[0]], Edge{f[1], minutes})
		g[f[1]] = append(g[f[1]], Edge{f[0], minutes})
	}

	// TODO: Dijkstra from start (import "container/heap") that also keeps
	// from[place] = the place it was best reached from. Then walk back from goal,
	// turn the route around, and print it as "a -> b -> c", then "N minutes".
	fmt.Println(start, "->", goal)
}
Go runtime not loaded yet

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