Problem Solving with Go course

GraphsGraphs as Adjacency Lists

Problem Solving with Go

Display

Theme

Graphs · Test exercise

Graphs as Adjacency Lists

A grid is a special case of something more general: a graph. A graph is a set of nodes (places, people, tasks) joined by edges (roads, friendships, "must happen before"). Trail maps, flight routes, wires between machines and dependencies between steps are all graphs, and puzzles often hand you one line per edge.

Storing a graph

The most useful form for puzzles is an adjacency list: for each node, the list of nodes it's joined to. In Go, a map from name to slice:

g := map[string][]string{}
for _, line := range lines {
	a, b, _ := strings.Cut(line, "-")
	g[a] = append(g[a], b)
	g[b] = append(g[b], a) // the trail goes both ways
}

Adding to g[a] works even when a isn't in the map yet: reading a missing key gives a nil slice, and append on nil makes a new one.

Whether to add the second line depends on the puzzle. A trail or a cable joins two nodes both ways (an undirected graph). A one-way street or "a must happen before b" only goes from a to b (a directed graph).

Clean it up as you read

Input is rarely perfect. Two habits save a lot of debugging later:

  • Check every line. A line without the separator, or with an empty name, is a bug in your parsing or in the input; report it instead of carrying on with a strange graph.
  • Decide what a repeated edge means. If the same trail is listed twice (perhaps once as oak-mill and once as mill-oak), adding it twice gives mill two copies of oak, and anything that counts neighbours is wrong.

Sorting each neighbour list makes the output stable: Go's maps have no order, so without sorting the same program can print a different order every time.

The degree of a node

The number of edges at a node is its degree: len(g[name]). A node of degree 1 is a dead end, a node of degree 0 is cut off, and high-degree nodes are hubs.

Task

This lesson's input is a trail map: each line joins two junctions, such as oak-pond. Trails go both ways.

  1. Complete parseGraph(lines []string) (map[string][]string, error): the adjacency list, with every neighbour list sorted A to Z and a trail listed twice counted once. A line that isn't two different, non-empty names joined by a single - is an error.
  2. Complete busiest(g) (string, int): the junction with the most trails and how many it has. On a tie, the name that comes first A to Z wins.
  3. Complete deadEnds(g) []string: the junctions with exactly one trail, sorted A to Z.
main.go
package main

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

// parseGraph reads trails such as "oak-pond", which join two junctions both ways. Every
// junction's neighbours are sorted A to Z, and a trail listed twice counts once. A line
// that isn't two different, non-empty names joined by "-" is an error.
func parseGraph(lines []string) (map[string][]string, error) {
	// TODO: add each trail in both directions, then sort every neighbour list
	return map[string][]string{}, nil
}

// busiest returns the junction with the most trails and how many it has. On a tie,
// the name that comes first A to Z wins.
func busiest(g map[string][]string) (string, int) {
	// TODO
	return "", 0
}

// deadEnds returns the junctions with exactly one trail, sorted A to Z.
func deadEnds(g map[string][]string) []string {
	// TODO
	return nil
}

func main() {
	var lines []string
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		if line := strings.TrimSpace(scanner.Text()); line != "" {
			lines = append(lines, line)
		}
	}
	g, err := parseGraph(lines)
	if err != nil {
		fmt.Println(err)
		return
	}
	names := make([]string, 0, len(g))
	for name := range g {
		names = append(names, name)
	}
	slices.Sort(names)
	for _, name := range names {
		fmt.Printf("%-7s → %s\n", name, strings.Join(g[name], ", "))
	}
	name, n := busiest(g)
	fmt.Println("busiest junction:", name, "with", n, "trails")
	fmt.Println("dead ends:", deadEnds(g))
}
Go runtime not loaded yet

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