思路
用一个visited数组保存每个城市被访问的情况,0代表未被访问,1代表被访问; 用一个distance数组来存储任意两个城市之间的距离; 用minDistance来表示当前遍历出的最小距离,对应城市为minDistanceCity; 用cityVistited存储已经经过的城市数; 用currentCity表示当前所在的城市。
代码实现
public int TSP(int[][] distance
) {
int[] visited
= new int[distance
.length
];
int sum
= 0;
int currentCity
= 0;
int cityVisited
= 1;
visited
[currentCity
] = 1;
while (cityVisited
< distance
.length
) {
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
;
}
转载请注明原文地址: https://yun.8miu.com/read-33673.html