Breadth-first search (BFS)

Explore the places you can reach in one step, two steps and so on. On a map of islands and bridges, this shows which islands are closest when you count bridge crossings.

Start on one island and line up its neighbors. Take the first island in line and add its new neighbors at the back. Nearby islands get their turn before distant ones.

An island is a vertex and a bridge is an edge. Mark a vertex as soon as you find it, so a cycle cannot send you around forever. Islands with no path from the start remain unvisited.

Each edge appears in two neighbor lists, once at each end. For V vertices and E edges, traversal takes O(V + E) time.