Nearest Neighbor Algorithm — Definition, Formula & Examples
The nearest neighbor algorithm is a quick way to plan a round trip through every city on a map. From wherever you are, you travel to the closest place you have not visited yet, and once every place is visited you return to the start.
Let be a complete weighted graph with vertices and a chosen start vertex . The algorithm builds a Hamiltonian cycle . At each step, is chosen to minimize over all unvisited vertices , with ties broken arbitrarily. It is a greedy heuristic for the Traveling Salesman Problem (TSP). It runs in time but does not guarantee a minimum-weight cycle.
Worked Example
Problem: A complete graph has vertices A, B, C, D with edge weights AB = 1, AC = 4, AD = 10, BC = 2, BD = 5, CD = 3. Use the nearest neighbor algorithm starting at A. Find the tour and its total weight, then compare it with the shortest possible tour.
Step 1: Start at A. The edges to unvisited vertices are AB = 1, AC = 4, AD = 10. The smallest is AB, so move to B.
Step 2: From B, the unvisited vertices are C and D, with BC = 2 and BD = 5. Move to C.
Step 3: From C, only D remains, so take CD = 3. Every vertex is now visited, so add the return edge DA = 10.
Answer: The nearest neighbor tour is A → B → C → D → A, with total weight 16. A complete graph on 4 vertices has only distinct tours, so you can check them all. The tour A → B → D → C → A has weight . The greedy choices forced the costly final edge DA = 10, so the algorithm missed the optimal tour.
Why It Matters
Checking every tour takes cycles, which is far too many even for 20 cities. Nearest neighbor gives a usable tour in seconds. Delivery-routing software and circuit-board drilling planners often use it as a starting tour, then improve it with methods such as 2-opt. In a discrete math course, it is also the standard example of a greedy algorithm that can fail to find the best answer.
Common Mistakes
Mistake: Stopping after the last new vertex and forgetting the edge back to the start.
Correction: A TSP tour is a cycle, so you must add the return edge. In the example, leaving out DA = 10 would report 6 instead of 16 and hide why the tour is poor.
