solve the traveling salemans problem in csharp

One way to solve the Traveling Salesman Problem (TSP) is to use a brute force approach to calculate the shortest path through all of the cities. However, when the number of cities grows, this approach becomes computationally infeasible due to the large number of possible paths.

Another approach is to use a heuristic algorithm such as the Nearest Neighbor or 2-Opt algorithm. The Nearest Neighbor algorithm starts at an arbitrary city and repeatedly selects the closest city until all cities have been visited. The 2-Opt algorithm improves on the path found by the Nearest Neighbor algorithm by swapping two edges in the path to see if the new path results in a shorter distance.

Here is a sample implementation of the Nearest Neighbor algorithm in C#:

main.cs
public static List<int> NearestNeighborAlgorithm(int startCity, double[,] distanceMatrix)
{
    int numCities = distanceMatrix.GetLength(0);
    bool[] visitedCities = new bool[numCities];
    List<int> path = new List<int>();
    path.Add(startCity);
    visitedCities[startCity] = true;

    while (path.Count < numCities)
    {
        int lastCity = path[path.Count - 1];
        int nearestCity = FindNearestCity(lastCity, visitedCities, distanceMatrix);
        path.Add(nearestCity);
        visitedCities[nearestCity] = true;
    }

    return path;
}

private static int FindNearestCity(int city, bool[] visitedCities, double[,] distanceMatrix)
{
    double shortestDistance = double.MaxValue;
    int nearestCity = -1;
    for (int i = 0; i < distanceMatrix.GetLength(0); i++)
    {
        if (!visitedCities[i] && distanceMatrix[city, i] < shortestDistance)
        {
            shortestDistance = distanceMatrix[city, i];
            nearestCity = i;
        }
    }
    return nearestCity;
}
1007 chars
34 lines

This implementation takes in a starting city and a distance matrix as inputs, and returns a list of integers representing the order in which the cities should be visited.

gistlibby LogSnag