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.
Metro region
A hundred towns, T1 to T100, where T stands for town, numbered row by row from the top left with ten to a row. Two fast motorways cross at T45: one runs from T41 to T50, the other through T5, T15 and on down to T95. Local roads join neighboring towns, a few of them one way, and each edge is the travel time in minutes.
A directed, weighted graph with 100 vertices and 346 edges.
List the towns you can reach from T45, where the two motorways cross, nearest by travel time first.
From T45, closest-first visits 100 vertices, nearest first: T45, T35, T55, T44, T46, T25, T65, T43, T47, T15, and so on to T100.
Step by step
- Every distance starts at ∞, except T45, which is 0. Put T45 in the queue at 0.
- Take T45 from the front of the queue and visit it. Its distance is 0.
- T45 to T35: 0 + 2 = 2. Put T35 in the queue at 2.
- T45 to T44: 0 + 3 = 3. Put T44 in the queue at 3.
- T45 to T46: 0 + 3 = 3. Put T46 in the queue at 3.
- T45 to T55: 0 + 2 = 2. Put T55 in the queue at 2.
268 more steps lead to the last one:
- Done. Closest-first visited 100 vertices from T45, nearest first.
Use it in Go
for v, dist := range traverse.ClosestFirst(g, "T45") {
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.