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-milland once asmill-oak), adding it twice givesmilltwo copies ofoak, 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.
- 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. - 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. - Complete
deadEnds(g) []string: the junctions with exactly one trail, sorted A to Z.