Connected Components
"How many separate groups are there?" Friends who know each other through friends, islands joined by bridges, machines on the same network: the groups are the connected components of a graph. Two nodes are in the same component when some path of edges joins them, however long.
One search per group
You already know the method from flood fill on a grid. A graph only changes how you find the neighbours: instead of four directions, read g[name].
seen := map[string]bool{start: true}
queue := []string{start}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
for _, next := range g[cur] {
if !seen[next] {
seen[next] = true
queue = append(queue, next)
}
}
}
// seen now holds start's whole component
BFS or DFS both work, because only which nodes are reached matters, not the order. To split the whole graph into groups, go through the nodes, and start a new search from every node that no earlier search has reached.
Don't forget the loners
A node without edges is a component of its own. If the graph is built only from lines like a-b, a node that never appears in an edge is missing from the map entirely, and the count comes out too low. When the input lists such nodes, put them in the map with an empty neighbour list.
A stable answer
Go's maps have no order, so "go through the nodes" visits them in a different order every run. If the puzzle wants the groups listed, sort the names first and the groups come out the same every time. Here each group is sorted A to Z, and the groups are ordered by their first name.
Task
This lesson's input lists the power cables on a small island. A line like bakery-school is a cable between two buildings, and a line with a single name is a building with no cable at all. The adjacency list is built for you.
- Complete
groupOf(g, start string) []string: every building joined tostartthrough any number of cables,startincluded, sorted A to Z. - Complete
components(g) [][]string: all the groups, each sorted A to Z, in order of their first name.