learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Ant Colony Optimization Visualizer for the TSP

Pheromone finds short tours

Ants build tours at random, favouring short hops and strong pheromone, and every tour lays pheromone in proportion to how short it is

Time: O(k · n³)
Space: O(n²)
Use Case: Travelling salesman, vehicle routing, scheduling
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Ant Colony Optimization (TSP)

Ant colony optimization (ACO) is a metaheuristic inspired by the way real ants find short paths between their nest and food. Ants lay pheromone as they walk and other ants prefer stronger trails, so the shortest path, which is walked fastest and most often, ends up with the most pheromone. Marco Dorigo turned this into an algorithm in his 1992 PhD thesis, and the Ant System of Dorigo, Maniezzo and Colorni (1996) applied it to the travelling salesman problem: find the shortest tour that visits every city once. ACO is a classic of swarm intelligence, taught in AI and operations research courses next to genetic algorithms and simulated annealing.

How it works

In each iteration every ant builds a complete tour. From city i it moves to an unvisited city j at random, with probability proportional to τ(i,j)^α × (1/d(i,j))^β: the pheromone τ on the pair, and the closeness of the city, here with α = 1 and β = 2. When all ants are done, every trail evaporates by the factor ρ = 0.5 and each ant adds 1/L to the pairs of its tour, L its length, so short tours deposit more. Over the iterations the pheromone gathers on the edges of good tours and the ants follow them more often, while evaporation lets the colony forget poor choices. The visualizer sends one ant from each city for 20 iterations, with a fixed random seed, and draws the pheromone as green lines whose width shows its strength.

Applications

ACO solves routing problems: vehicle routing with time windows, packet routing in communication networks (AntNet), and the planning of trucks, buses and deliveries. It also handles assignment and scheduling problems such as quadratic assignment, job shop scheduling and timetabling, and has been applied to protein folding and to feature selection in machine learning. Its strengths are that it adapts to changing data, since the trails simply shift, and that it combines well with local search such as 2-opt. Like other metaheuristics it finds good tours fast but proves nothing about optimality, which is why it is checked against exact methods on small instances, as this visualizer does.

Pseudocode

The Ant System repeats two phases: every ant builds a tour with random choices biased by pheromone and distance, then the pheromone evaporates and every tour deposits on its edges.

AntSystem(cities, α = 1, β = 2, ρ = 0.5, iterations):
    τ[i][j] = n / L_nn for every pair      // L_nn: nearest-neighbour tour
    best = none
    repeat iterations times:
        for each ant k = 1..n:
            tour = [city k]
            while some city is unvisited:
                i = last city of tour
                choose an unvisited j with probability
                    ∝ τ[i][j]^α × (1 / d[i][j])^β
                append j to tour
            keep tour as best if it is shorter
        τ = (1 - ρ) × τ                    // evaporation
        for each ant: add 1 / L to τ on the edges of its tour
    return best

α weighs the pheromone and β the distance. With α = 0 the ants ignore the trails and act as a randomized nearest-neighbour heuristic. With β = 0 they follow pheromone alone and soon lock onto a poor tour. Ant Colony System and the MAX-MIN Ant System, stronger later variants, deposit only on the best tour and bound τ to avoid that stagnation.

Worked example, step by step

Load the example: nine cities with distances taken from the drawing, every pair connected.

Example graph: The cities A to I lie roughly on a loop, with H and I inside it. The nearest-neighbour tour from A has length 109, and the shortest tour, checked by dynamic programming, has length 95.

  1. Start. Every pair gets the same pheromone, τ0 = 9 / 109 = 0.083. With equal trails the first choices depend only on distance: from A the ant picks B with probability 30% and G with 22%, but it may still go to H (19%), and it does.
  2. Iteration 1. The nine ants build tours between 108 and 145 long. Then every trail loses half its pheromone and each ant adds 1 / L along its tour, so the edges of short tours, and of tours that several ants share, end up stronger.
  3. Iterations 2 to 11. The best ant drops to 97 in iteration 2. The colony keeps trying variations around the strong trails, and in iteration 11 an ant builds 95, the optimal tour A, B, C, I, D, E, F, H, G.
  4. Iterations 12 to 20. Several later iterations rebuild the 95 tour. The average tour drops from 127 to about 110, and the strongest trails, A-B, F-H, A-G and D-E, are all edges of the optimal tour.

The colony found the optimal tour of length 95, 13% shorter than the nearest-neighbour tour, in iteration 11. On nine cities an exact method is still instant. ACO earns its keep on instances with hundreds or thousands of cities, where exact methods are out of reach, usually combined with local search such as 2-opt.

Complexity, and where it comes from

Time: O(k · n³) · Space: O(n²)

Building one tour takes n choices, each over up to n candidate cities, so O(n²). With n ants that makes O(n³) per iteration, and the pheromone update adds O(n²). Over k iterations the total is O(k · n³), here 20 × 9³, about 15,000 basic steps. The pheromone and distance matrices take O(n²) memory. Real implementations restrict each choice to a candidate list of the 10 to 20 nearest cities, which brings a tour down to about O(n) and makes thousands of cities practical.

When to use Ant Colony Optimization (TSP), and when not to

ACO is one of several ways to attack the travelling salesman problem. Exact methods prove optimality, heuristics trade that for speed.

AlternativePrefer it whenCost
Exact dynamic programming (Held-Karp)Up to about 20 cities, when the optimum must be proven.O(n² · 2ⁿ)
ChristofidesA guarantee: a tour at most 1.5 times the optimum when distances obey the triangle inequality.O(n³)
2-opt and Lin-KernighanFast and very good tours in practice, often as the finishing step of other methods.O(n²) per pass
Ant colony optimizationLarge or changing instances and routing variants with extra constraints, combined with 2-opt.O(k · n³), less with candidate lists

Common pitfalls

  • Stagnation. If the pheromone piles up on one tour too fast, every ant builds that tour and the search stops. Evaporation, bounds on τ (MAX-MIN Ant System) and a pheromone reset when progress stalls keep the colony exploring.
  • Parameter sensitivity. α, β, ρ and the number of ants interact, and poor values give poor tours. Common starting points are α = 1, β between 2 and 5, ρ around 0.5 and as many ants as cities, tuned afterwards on your own instances.
  • No optimality guarantee. The best tour found may be the optimum or a few percent above it, and ACO cannot tell which. Use a lower bound such as the Held-Karp bound, or an exact solver on small instances, to measure the gap.
  • Randomness. Two runs with different seeds give different tours. Report the best and the average of several runs, and fix the seed when results must be repeatable, as this visualizer does.

Frequently asked questions

How does ant colony optimization work?
Artificial ants build solutions step by step, choosing each next element at random with a bias toward short steps and strong pheromone. Good solutions deposit more pheromone, which makes their parts more likely to be chosen again, while evaporation slowly erases old choices.
Is ant colony optimization better than a genetic algorithm?
Neither is better in general. ACO builds solutions element by element, which suits routing and sequencing problems such as the TSP. Genetic algorithms recombine whole solutions and suit problems with a natural encoding. For the TSP the best results come from either method combined with local search.
What do α, β and ρ mean?
α is the weight of the pheromone in the choice rule, β the weight of the distance, and ρ the evaporation rate, the share of pheromone that disappears after each iteration. A higher β makes the ants greedier, a higher ρ makes the colony forget faster.
Who invented ant colony optimization?
Marco Dorigo proposed it in his PhD thesis at the Politecnico di Milano in 1992. The Ant System paper with Vittorio Maniezzo and Alberto Colorni appeared in 1996, and Ant Colony System (Dorigo and Gambardella, 1997) made the method competitive on large TSP instances.

Related algorithms: Traveling Salesman Problem, Christofides, Hamiltonian Path, Fleet Dispatching (mTSP)

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 9
Edges: 36