salesman problem in csharp

The salesman problem, also known as the traveling salesman problem, is a classic problem in graph theory and optimization. It seeks to find the shortest possible route that visits each of a set of locations exactly once and returns to the original location.

One common approach to solving the salesman problem is to use a technique called dynamic programming. Here is an example implementation of the salesman problem using dynamic programming in C#:

main.cs
using System;

class Salesman
{
    static int[,] distances = { { 0, 10, 15, 20 },
                                { 10, 0, 35, 25 },
                                { 15, 35, 0, 30 },
                                { 20, 25, 30, 0 } };

    static int[,] memo;

    static int tsp(int mask, int pos)
    {
        if (mask == (1 << distances.GetLength(0)) - 1)
            return distances[pos, 0];

        if (memo[mask, pos] != -1)
            return memo[mask, pos];

        int res = int.MaxValue;
        for (int next = 0; next < distances.GetLength(0); next++)
        {
            if ((mask & (1 << next)) == 0)
            {
                int newMask = mask | (1 << next);
                int route = distances[pos, next] + tsp(newMask, next);
                res = Math.Min(res, route);
            }
        }

        memo[mask, pos] = res;
        return res;
    }

    static void Main()
    {
        memo = new int[1 << distances.GetLength(0), distances.GetLength(0)];
        for (int i = 0; i < memo.GetLength(0); i++)
            for (int j = 0; j < memo.GetLength(1); j++)
                memo[i, j] = -1;
        Console.WriteLine(tsp(1, 0));
        Console.ReadLine();
    }
}
1208 chars
45 lines

In this implementation, distances is a two-dimensional array that represents the distances between each pair of locations. The tsp method uses dynamic programming to recursively calculate the shortest route that visits all locations, given a current location and a bitmask that indicates which locations have already been visited. The result is stored in a memo array to avoid duplicate calculations.

The main method initializes the memo array and calls tsp to find the shortest route that visits all locations, starting and ending at the first location. The output is the length of the shortest route.

gistlibby LogSnag