Closest-first
Visits vertices in order of their distance from a start vertex, nearest first.
Time complexity O(E log V), gograph function traverse.ClosestFirst.
traverse.NewClosestFirstIterator gives the same order one Next at a time, without the distances.
How it works
Closest-first keeps a priority queue of vertices by their distance from the start, the sum of the edge weights along the best path found so far. It takes the nearest vertex it hasn't visited, then puts each unvisited neighbor in the queue at the distance through that vertex, or moves it up the queue if that distance is shorter than the one it has. The vertices come out in order of distance, nearest first.
It is Dijkstra's algorithm as an iterator. traverse.ClosestFirst returns an iter.Seq2 of each vertex with its distance, and each one it yields is final, so a range loop can break at the vertex it needs without settling the rest of the graph. It costs O(E log V). Edge weights must not be negative, or a vertex can come out before a cheaper path to it is found.
Use it when the order matters, such as the three stores nearest to a home, and path.Dijkstra when you need the distance to every vertex at once.
Delivery area
Eight stops in a small town. Streets are one way, and each edge is the travel time in minutes.
A directed, weighted graph with 8 vertices and 12 edges.
List the stops a driver can reach from the depot, nearest by travel time first.
From Depot, closest-first visits 8 vertices, nearest first: Depot, Market, Bakery, School, Park, Library, Clinic and Station.
Step by step
- Every distance starts at ∞, except Depot, which is 0. Put Depot in the queue at 0.
- Take Depot from the front of the queue and visit it. Its distance is 0.
- Depot to Bakery: 0 + 4 = 4. Put Bakery in the queue at 4.
- Depot to Market: 0 + 2 = 2. Put Market in the queue at 2.
- Take Market from the front of the queue and visit it. Its distance is 2.
- Market to Bakery: 2 + 1 = 3, shorter than 4. Move Bakery up the queue to 3.
15 more steps lead to the last one:
- Done. Closest-first visited 8 vertices from Depot, nearest first.
Use it in Go
for v, dist := range traverse.ClosestFirst(g, "Depot") {
fmt.Println(v.Label(), dist)
}
Example graphs
- School run, 6 vertices and 13 edges
- Delivery area, 8 vertices and 12 edges
- Downtown grid, 20 vertices and 60 edges
- One-way city, 45 vertices and 88 edges
- Metro region, 100 vertices and 346 edges
More in Traversal
- Breadth-first: Visits vertices level by level from a start vertex.
- 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.
- Random walk: Moves from a start vertex to a random out-neighbor again and again, with heavier edges more likely.