Problem Solving with Go course

GraphsConnected Components

Problem Solving with Go

Display

Theme

Graphs · Test exercise

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.

  1. Complete groupOf(g, start string) []string: every building joined to start through any number of cables, start included, sorted A to Z.
  2. Complete components(g) [][]string: all the groups, each sorted A to Z, in order of their first name.
main.go
package main

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

// groupOf returns every building joined to start through any number of cables,
// start included, sorted A to Z.
func groupOf(g map[string][]string, start string) []string {
	// TODO: BFS or DFS from start with a set of names seen
	return []string{start}
}

// components splits the buildings into groups that are joined to each other. Each group
// is sorted A to Z, and the groups are in order of their first name.
func components(g map[string][]string) [][]string {
	// TODO: go through the names A to Z and start a group at each one not seen yet
	return nil
}

func main() {
	g := map[string][]string{}
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" {
			continue
		}
		a, b, cable := strings.Cut(line, "-")
		if !cable {
			if _, known := g[a]; !known {
				g[a] = nil // a building without cables is still on the map
			}
			continue
		}
		g[a] = append(g[a], b)
		g[b] = append(g[b], a)
	}
	groups := components(g)
	fmt.Println(len(groups), "power networks:")
	for _, group := range groups {
		fmt.Println(" ", strings.Join(group, ", "))
	}
}
Go runtime not loaded yet

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