Traveling Salesman Problem Solution by Greedy Method

tsp_greedy, a MATLAB program which applies a simple greedy algorithm to construct a solution to the traveling salesman problem.

The user must prepare a file beforehand, containing the city-to-city distances. The program will request the name of this file, and then read it in as a matrix d. An example of such a file is:

        0  3  4  2  7
        3  0  4  6  3
        4  4  0  5  8
        2  6  5  0  6
        7  3  8  6  0
The distance file d should be square, symmetric, and have a zero diagonal.

A tour of n cities can be represented as a permutation p on the integers 1 through n. The cost of the tour, that is, the length, is the sum

        cost = sum ( 1 <= i <= n ) ( d(p(i),p(i+1)) )
where p(n+1) is understood to mean p(1).

The greedy algorithm starts at one of the cities, and then successively moves to the nearest unvisited city, producing a tour. The tour may depend on the starting city, and so all n cities are tried. At the end, the shortest observed tour is reported.


The computer code and data files described and made available on this web page are distributed under the GNU LGPL license.


tsp_greedy is available in a MATLAB version.

Related Data and Programs:

CHANGE_MAKING, a MATLAB library which considers the change making problem, in which a given sum is to be formed using coins of various denominations.

CITIES, a MATLAB library which handles various problems associated with a set of "cities" on a map.

COMBINATION_LOCK, a MATLAB program which simulates the process of determining the secret combination of a lock.

PARTITION_PROBLEM, a MATLAB library which seeks solutions of the partition problem, splitting a set of integers into two subsets with equal sum.

SATISFY, a MATLAB program which demonstrates, for a particular circuit, an exhaustive search for solutions of the circuit satisfiability problem.

SUBSET_SUM, a MATLAB library which seeks solutions of the subset sum problem.

TSP, a dataset directory which contains test data for the traveling salesperson problem;

tsp_brute, a MATLAB program which reads a file of city-to-city distances and solves the traveling salesperson problem, using brute force.

tsp_descent, a MATLAB program which is given a city-to-city distance map, chooses an initial tour at random, and then tries a number of simple variations, seeking to quickly find a tour of lower cost.


tsp_random, a MATLAB program which reads a file of city-to-city distances, and then randomly samples a number of possible tours, to quickly seek a tour of lower length.


  1. Gerhard Reinelt,
    TSPLIB - A Traveling Salesman Problem Library,
    ORSA Journal on Computing,
    Volume 3, Number 4, Fall 1991, pages 376-384.

Source Code:

Last revised on 24 April 2019.