44 lines
1.5 KiB
C
44 lines
1.5 KiB
C
|
|
#include <stdio.h>
|
||
|
|
#include <limits.h>
|
||
|
|
#define MAX_CITIES 4 // 城市数量
|
||
|
|
#define INF INT_MAX
|
||
|
|
int n = MAX_CITIES; // 城市数量
|
||
|
|
int dist[MAX_CITIES][MAX_CITIES] = {
|
||
|
|
{0, 30, 6, 4}, {30, 0, 5, 10},
|
||
|
|
{6, 5, 0, 20}, {4, 10, 20, 0}
|
||
|
|
};
|
||
|
|
int visited[MAX_CITIES]; // 标记城市是否访问
|
||
|
|
int bestPath[MAX_CITIES]; // 最优路径
|
||
|
|
int bestCost = INF; // 最优路径的总成本
|
||
|
|
// 回溯法求解TSP
|
||
|
|
void backtrack(int currentCity, int count, int cost, int path[]) {
|
||
|
|
if (count == n) { // 所有城市都已访问,检查是否是最优解
|
||
|
|
cost += dist[currentCity][0]; // 加上返回起点的距离
|
||
|
|
if (cost < bestCost) {
|
||
|
|
bestCost = cost;
|
||
|
|
for (int i = 0; i < n; i++)
|
||
|
|
bestPath[i] = path[i];
|
||
|
|
}
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
for (int i = 0; i < n; i++) {// 尝试所有未访问的城市
|
||
|
|
if (!visited[i]) { // 访问城市i
|
||
|
|
visited[i] = 1; path[count] = i;
|
||
|
|
// 递归访问下一个城市
|
||
|
|
backtrack(i, count + 1, cost + dist[currentCity][i], path);
|
||
|
|
visited[i] = 0; // 回溯
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
int main() {
|
||
|
|
int path[MAX_CITIES];
|
||
|
|
visited[0] = 1; // 从第一个城市出发
|
||
|
|
path[0] = 0; // 起点是城市0
|
||
|
|
backtrack(0, 1, 0, path); // 从城市0开始回溯
|
||
|
|
printf("\n最优路径是: ");
|
||
|
|
for (int i = 0; i < n; i++)
|
||
|
|
printf("%d ", bestPath[i]);
|
||
|
|
printf("\n最小路程: %d\n", bestCost);
|
||
|
|
return 0;
|
||
|
|
}
|