Advanced topics · Exercise 100 of 100

Graph connectivity

To test a nonempty undirected graph for connectivity, start at any vertex and mark it visited. From each newly visited vertex, follow every edge to a neighbor you have yet to visit. When the search runs out of neighbors to explore, the graph is connected exactly when every vertex has been marked.

Try it yourself

Five stops named ash, bay, elm, fir and oak have two-way links ash–bay, bay–elm, elm–ash and fir–oak. Starting at bay, how many stops remain unvisited after a full search?

One-step hint

Mark bay, then follow links from each marked stop to any unmarked neighbor. When that search runs out, count the unmarked stops.

Worked solution
  1. From bay the search reaches ash and elm. Their links lead back to stops in the same triangle.
  2. There is no link from that triangle to fir or oak, so those 2 stops remain unvisited.
DSA compiler