#include <stdio.h> #include <stdlib.h> #define MAXN 1000 #define INF 0x3f3f3f3f int n, m; int graph[MAXN][MAXN]; int path[MAXN]; int dist; void dfs(int u, int depth, int distance, int visited[]) { if (depth == n) { if (graph[u][1] != INF && distance + graph[u][1] < dist) { dist = distance + graph[u][1]; for (int i = 1; i <= n; i++) { printf("%d ", path[i]); } printf("1\n"); } return; } for (int v = 2; v <= n; v++) { if (!visited[v] && graph[u][v] != INF) { visited[v] = 1; path[depth+1] = v; dfs(v, depth+1, distance+graph[u][v], visited); visited[v] = 0; } } } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { graph[i][j] = INF; } } for (int i = 1; i <= m; i++) { int x, y, z; scanf("%d,%d,%d", &x, &y, &z); graph[x][y] = graph[y][x] = z; } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (graph[i][k] != INF && graph[k][j] != INF && graph[i][k] + graph[k][j] < graph[i][j]) { graph[i][j] = graph[i][k] + graph[k][j]; } } } } int visited[MAXN] = {0}; visited[1] = 1; path[1] = 1; dist = INF; dfs(1, 1, 0, visited); printf("%d\n", dist); return 0; }修改改代码,使其只显示最短路径
时间: 2023-12-21 20:03:47 浏览: 80
#include <stdio.h>
4星 · 用户满意度95%
可以在dfs函数中加入一个变量来记录当前的最短路径长度,每次更新路径时判断是否比当前最短路径更短。同时,在找到最短路径后就直接return,不再继续搜索其他路径。
修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXN 1000
#define INF 0x3f3f3f3f
int n, m;
int graph[MAXN][MAXN];
int path[MAXN];
int dist;
int shortest_dist = INF;
void dfs(int u, int depth, int distance, int visited[]) {
if (depth == n) {
if (graph[u][1] != INF && distance + graph[u][1] < shortest_dist) {
shortest_dist = distance + graph[u][1];
dist = distance + graph[u][1];
for (int i = 1; i <= n; i++) {
path[i] = i;
}
path[n+1] = 1;
}
return;
}
for (int v = 2; v <= n; v++) {
if (!visited[v] && graph[u][v] != INF) {
visited[v] = 1;
path[depth+1] = v;
dfs(v, depth+1, distance+graph[u][v], visited);
visited[v] = 0;
}
}
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
graph[i][j] = INF;
}
}
for (int i = 1; i <= m; i++) {
int x, y, z;
scanf("%d,%d,%d", &x, &y, &z);
graph[x][y] = graph[y][x] = z;
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (graph[i][k] != INF && graph[k][j] != INF && graph[i][k] + graph[k][j] < graph[i][j]) {
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}
int visited[MAXN] = {0};
visited[1] = 1;
path[1] = 1;
dfs(1, 1, 0, visited);
printf("%d\n", dist);
for (int i = 1; i <= n+1; i++) {
printf("%d ", path[i]);
}
printf("\n");
return 0;
}
```
阅读全文