Prolog Implementation of the Traveling Salesperson Problem: Exact and Heuristic Solvers
Summary
This document shows how to solve the Traveling Salesperson Problem in Prolog using two methods: an exact brute-force search that finds the shortest tour, and a faster Nearest Neighbor heuristic that gives a good but not always optimal route. It includes the code for each approach, explains how tour costs are computed, and provides sample queries to compare the results.
Key points
- Distances between cities are stored as dist/3 facts and made symmetric with a rule.
- path_cost/2 recursively sums the distances between consecutive cities in a tour.
- tsp/3 generates all tours using select/3 and permutation/2, and shortest_tsp/3 collects them with findall/3 and sorts by cost.
- The brute-force solver guarantees the optimal tour but becomes slow as the number of cities grows.
- The Nearest Neighbor heuristic always moves to the closest unvisited city, which is much faster but may not give the global optimum.
- The code assumes reverse/2 is available, for example from library(lists).
This document presents two distinct approaches to solving the Traveling Salesperson Problem (TSP) using Prolog: an exact, brute-force method and a heuristic-based Nearest Neighbor algorithm. Both implementations are demonstrated with code and sample queries.
Exact Solver: Brute-Force TSP Algorithm
This section details a Prolog program that finds the optimal (shortest) path for the Traveling Salesperson Problem by generating and evaluating all possible tours. This method guarantees the optimal solution but can be computationally intensive for larger sets of cities.
Defining City Distances in Prolog
The distances between cities are defined using dist/3 facts. The predicate is made symmetric to ensure that dist(X,Y,D) implies dist(Y,X,D).
dist(a,b,10).
dist(a,c,15).
dist(a,d,20).
dist(b,c,35).
dist(b,d,25).
dist(c,d,30).
dist(X,Y,D) :- dist(Y,X,D). % Ensures symmetry in distances
Calculating Tour Path Cost
The path_cost/2 predicate recursively calculates the total cost of a given tour path by summing the distances between consecutive cities.
path_cost([_],0).
path_cost([A,B|T],Cost) :-
dist(A,B,D),
path_cost([B|T],C),
Cost is D+C.
Generating All Possible TSP Tours
The tsp/3 predicate generates all possible tours starting and ending at a specified Start city. It uses Prolog's built-in select/3 and permutation/2 predicates to explore all permutations of the remaining cities.
tsp(Start,Path,Cost) :-
Cities = [a,b,c,d],
select(Start,Cities,Rest),
permutation(Rest,Perm),
append([Start|Perm],[Start],Path),
path_cost(Path,Cost).
Identifying the Shortest TSP Tour
The shortest_tsp/3 predicate finds the tour with the minimum cost. It collects all possible tours and their costs using findall/3 and then sorts them to retrieve the shortest one.
shortest_tsp(Start,BestPath,MinCost) :-
findall((P,C),tsp(Start,P,C),List),
sort(2,@=<,List,[(BestPath,MinCost)|_]).
Sample Query & Output: Exact TSP Solver
Here is an example query to find the shortest path starting from city 'a' using the exact solver, along with its expected output:
?- shortest_tsp(a,Path,Cost).
Path = [a, b, d, c, a],
Cost = 80.
Heuristic Solver: Nearest Neighbor TSP
For larger problems, an exact solver can be too slow. Heuristic algorithms provide a faster, though not always optimal, solution. The Nearest Neighbor algorithm is a common choice for its simplicity and efficiency.
Nearest Neighbor Heuristic Explanation
- Approach: At each step, the algorithm picks the closest unvisited city from the current city.
- Efficiency: Significantly faster than a full search (brute-force) as it does not explore all possible paths.
- Optimality: May not always yield the globally optimal path, but often provides a good approximation.
Prolog Code for Nearest Neighbor TSP
This Prolog implementation of the Nearest Neighbor heuristic constructs a tour by iteratively selecting the closest unvisited city. Note that reverse/2 is assumed to be available (e.g., from library(lists)).
nearest_neighbor(Start,Path,TotalCost) :-
Cities = [a,b,c,d],
select(Start,Cities,Rest),
nn(Start,Rest,[Start],PathReversed,0,Cost1), % PathReversed will be [LastVisited, ..., Start]
reverse(PathReversed, PathOrdered), % PathOrdered will be [Start, ..., LastVisited]
append(PathOrdered,[Start],Path), % Final Path: [Start, ..., LastVisited, Start]
last(PathOrdered,Last), % Last city visited before returning to Start
dist(Last,Start,BackCost),
TotalCost is Cost1 + BackCost.
% Nearest neighbor helper predicate
nn(_,[],Path,Path,Cost,Cost).
nn(Current,CitiesLeft,AccPath,FinalPath,AccCost,FinalCost) :-
nearest(Current,CitiesLeft,Next,Dist),
select(Next,CitiesLeft,NewLeft),
NewCost is AccCost + Dist,
nn(Next,NewLeft,[Next|AccPath],FinalPath,NewCost,FinalCost).
% Find nearest city from Current among Cities
nearest(Current,Cities,Nearest,Dist) :-
findall((C,D),(member(C,Cities),dist(Current,C,D)),List),
sort(2,@=<,List,[(Nearest,Dist)|_]).
Sample Queries for Both TSP Methods
You can compare the results of the exact and heuristic solvers using these queries:
% Query for the exact shortest path:
?- shortest_tsp(a,Path,Cost).
% Query for the path found by the Nearest Neighbor heuristic:
?- nearest_neighbor(a,Path,Cost).
Download
PDF Word HTMLFAQ
Why does the exact TSP solver become slow with more cities?
It generates and evaluates every permutation of the remaining cities, so the number of tours grows factorially. For larger problems this becomes computationally intensive, which is why a heuristic is suggested.
Does the Nearest Neighbor algorithm always find the shortest tour?
No. At each step it picks the closest unvisited city, which is fast and often a good approximation, but it may not yield the globally optimal path.
Why is the dist/3 predicate made symmetric?
A rule ensures that dist(X,Y,D) implies dist(Y,X,D), so the distance between two cities can be looked up in either direction.
Test yourself
Flashcards
Click a card to see the answer.
Quiz
Questions generated by AI from the document: check the answers against the text.