Breadth-first

Visits vertices level by level from a start vertex.

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

Maze

A maze of 30 cells in five rows, A to E, and six columns, 1 to 6, so C4 is row C, column 4. Each edge is an open passage between two cells. The way from A1 to E6 winds through most of the maze, and two short loops give a few cells a second route.

An undirected graph with 30 vertices and 31 edges.

Starting at A1, find every cell of the maze, the cells fewest steps away first.

Use it in Go

it, err := traverse.NewBreadthFirstIterator(g, "A1")
if err != nil {
	return err
}
for it.HasNext() {
	fmt.Println(it.Next().Label())
}

Example graphs

More in Traversal

  • Depth-first: Follows one path as deep as it can, then continues from the most recently found vertex.
  • 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