TSP问题

    xiaoxiao2022-07-08  225

    思路

    用一个visited数组保存每个城市被访问的情况,0代表未被访问,1代表被访问; 用一个distance数组来存储任意两个城市之间的距离; 用minDistance来表示当前遍历出的最小距离,对应城市为minDistanceCity; 用cityVistited存储已经经过的城市数; 用currentCity表示当前所在的城市。

    代码实现

    public int TSP(int[][] distance) { // 1 represent the city has been visited // 0 represent the city hasn't been visited int[] visited = new int[distance.length]; int sum = 0; // current position is the city 0 int currentCity = 0; int cityVisited = 1; visited[currentCity] = 1; // make sure there are at least two cities while (cityVisited < distance.length) { // initialized minDistance int minDistance = Integer.MAX_VALUE; int minDistanceCity = Integer.MAX_VALUE; for (int j=0; j < visited.length; j++) { if (visited[j] == 0 && distance[currentCity][j] < minDistance && j != currentCity) { minDistance = distance[currentCity][j]; minDistanceCity = j; } } currentCity = minDistanceCity; sum += minDistance; cityVisited++; visited[currentCity] = 1; System.out.println(" " + currentCity); } System.out.println(); return sum; }
    最新回复(0)