Breadth-first

Visits vertices level by level from a start vertex.

Time complexity O(V+E), gograph function traverse.BFSWithDepth.

traverse.BFS gives the same order without the depths, and traverse.NewBreadthFirstIterator gives it one Next at a time. path.BFSPaths returns the route with the fewest edges to each vertex, the edges the steps draw.

How it works

Breadth-first search keeps a queue of the vertices it has found but not visited yet. It takes the vertex at the front and puts each neighbor it hasn't seen at the back. So every vertex one edge from the start comes out before any vertex two edges away, and so on, one level at a time.

When every edge counts the same, that order gives the fewest edges from the start to each vertex, such as the fewest hops between two machines. gograph marks a vertex as seen when it joins the queue, so each one is visited once and the search costs O(V+E). Vertices the start can't reach are never visited.

traverse.BFS and traverse.BFSWithDepth return an iter.Seq, so a range loop can break as soon as it finds what it needs, and BFSWithDepth gives each vertex with its number of edges from the start. path.BFSPaths runs the same search and keeps the edge that first found each vertex, so PathTo on its result gives a route with the fewest edges to any vertex, start first, and false for one out of reach. When edges have different weights, the fewest edges isn't the shortest route, and Closest-first or Dijkstra gives the real distances.

Home network

A router and the devices connected to it.

An undirected graph with 6 vertices and 6 edges.

Find every device the router can reach, the ones a single hop away first, as a network scan would.

From Router, breadth-first visits 6 vertices: Router, Laptop, Phone, TV, Printer and Speaker.

Step by step

  1. Start at Router. Put it in the queue.
  2. Take Router from the front of the queue.
  3. Add Laptop, Phone, TV and Printer, the unseen neighbors of Router, to the back of the queue.
  4. Take Laptop from the front of the queue.
  5. Laptop has no unseen neighbors.
  6. Take Phone from the front of the queue.

7 more steps lead to the last one:

  1. Done. Breadth-first reached 6 vertices from Router.

Use it in Go

for v, depth := range traverse.BFSWithDepth(g, "Router") {
	fmt.Println(v.Label(), depth)
}

paths, err := path.BFSPaths(g, "Router")
if err != nil {
	return err
}
route, _ := paths.PathTo("Speaker")
for _, v := range route {
	fmt.Println(v.Label())
}

Example graphs

More in Traversal

  • Depth-first: Follows one path as deep as it can, then backs up to the last vertex with a neighbor left to try, and sorts every edge it meets into four kinds.
  • Closest-first: Visits vertices in order of their distance from a start vertex, nearest first.
  • Random walk: Moves from a start vertex to a random out-neighbor again and again, with heavier edges more likely.

All algorithms