Problem Solving with Go course

GraphsDijkstra with container/heap

Problem Solving with Go

Display

Theme

Graphs · Test exercise

Dijkstra with container/heap

BFS finds the fewest steps. When every edge has its own cost (minutes, metres, coins), the fewest steps is no longer the cheapest route: one long road can lose to a chain of short ones. Dijkstra's algorithm is BFS for weighted graphs, as long as no cost is negative.

Always the nearest unsettled node

BFS takes nodes in the order they were found. Dijkstra takes them in order of cost so far: it always continues from the cheapest node it hasn't finished with. When a node is taken out that way, no cheaper route to it can turn up later, because every other route would start from a node that's already at least as expensive.

For "always give me the cheapest" you need a priority queue. Go has one in container/heap: you write five small methods on a slice type, and heap.Push and heap.Pop keep the cheapest entry on top.

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          { /* remove and return the last element */ }

Call heap.Push(q, v) and heap.Pop(q), not q.Push and q.Pop: the package functions keep the order, and your methods are only the building blocks they use. heap.Pop returns any, so take the value back out with .(visit).

The loop

best := map[string]int{start: 0}
q := &queue{{start, 0}}
for q.Len() > 0 {
	cur := heap.Pop(q).(visit)
	if cur.minutes > best[cur.town] {
		continue // a slower entry from before; this town was improved since
	}
	for _, e := range g[cur.town] {
		m := cur.minutes + e.Minutes
		if old, seen := best[e.To]; !seen || m < old {
			best[e.To] = m
			heap.Push(q, visit{e.To, m})
		}
	}
}

A town can be pushed several times, once for every improvement. Instead of removing old entries from the heap, the continue skips them when they come out. That's the simplest correct version, and the one most people write in puzzles.

Dijkstra costs about O(E log V) for E edges and V nodes. Grid puzzles with costs per cell work the same way: the nodes are cells, and the edges are moves to neighbours.

Task

This lesson's input lists roads between towns with how many minutes each takes. Roads go both ways. The queue type is ready.

  1. Complete distances(g, start) map[string]int: the fewest minutes from start to every town it can reach. Towns it can't reach are not in the map. You'll need to import container/heap.
  2. Complete shortest(g, start, goal) (int, bool): the fewest minutes from start to goal, and false when there's no way there.
main.go
package main

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

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

// visit is a town and the minutes it took to get there.
type visit struct {
	town    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
}

// distances returns the fewest minutes from start to every town it can reach.
// Towns it can't reach are not in the map.
func distances(g map[string][]Edge, start string) map[string]int {
	// TODO: heap.Push and heap.Pop on a *queue, starting with {start, 0}
	return map[string]int{start: 0}
}

// shortest returns the fewest minutes from start to goal, and false when goal can't
// be reached.
func shortest(g map[string][]Edge, start, goal string) (int, bool) {
	// TODO
	return 0, false
}

func main() {
	g := map[string][]Edge{}
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) != 3 {
			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}) // roads go both ways
	}
	for _, goal := range []string{"castle", "tower", "orchard"} {
		if m, ok := shortest(g, "harbour", goal); ok {
			fmt.Printf("harbour to %s: %d minutes\n", goal, m)
		} else {
			fmt.Printf("harbour to %s: no road\n", goal)
		}
	}
}
Go runtime not loaded yet

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