Breadth-first

Visits vertices level by level from a start vertex.

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

Karate club

The 34 members of a university karate club, numbered 1 to 34 as in the study. Each edge joins two members who also spent time together outside the club's classes and meetings. A dispute between the instructor (1) and an officer (34) split the club in two, and most members sit near the side they joined.

An undirected graph with 34 vertices and 78 edges.

News starts with the instructor, member 1, and each member passes it to everyone they spend time with. In what order do the members hear it?

Use it in Go

it, err := traverse.NewBreadthFirstIterator(g, "1")
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