C++ 如何在C语言中实现Dijkstra算法来寻找无向图中从一个节点到所有其他节点的最短路径,并打印距离
有一个无向图。您需要将所有边权重存储在二维数组cost[][]中,并计算从源节点0到所有其他节点的最短距离。假设最多有100个节点。如果两个节点之间没有边,我们将它们的权重设置为一个非常大的数字,MAX_DIS=999999,以表示这两个节点没有直接连接 在本练习中,您需要完成以下两项任务C++ 如何在C语言中实现Dijkstra算法来寻找无向图中从一个节点到所有其他节点的最短路径,并打印距离,c++,algorithm,graph,shortest-path,dijkstra,C++,Algorithm,Graph,Shortest Path,Dijkstra,有一个无向图。您需要将所有边权重存储在二维数组cost[][]中,并计算从源节点0到所有其他节点的最短距离。假设最多有100个节点。如果两个节点之间没有边,我们将它们的权重设置为一个非常大的数字,MAX_DIS=999999,以表示这两个节点没有直接连接 在本练习中,您需要完成以下两项任务 初始化成本数组 最初,我们使用数组成本[100][100]来存储边缘成本。我们输入总节点数n和边数m,并输入格式为的所有边,其中w是边的权重(x,y)。如果两个节点之间没有边,我们将设置代价MAX_DIS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_NODES 100
#define MAX_DIS 999999
int cost[MAX_NODES][MAX_NODES];
int distance[MAX_NODES];
void initial(int m, int n);
void Dijkstra(int n);
void initial(int m, int n)
{
/*
let user input all edges and their weights and initialize cost[][].
note that if no edge between (x,y), set cost[x][y]=MAX_DIS
and cost[a][b]=cost[b][a] for the undirected graph.
Fill in your code here...
*/
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cost[i][j] = MAX_DIS;
}
}
cost[0][0] = 0;
int weight,x,y;
for(i=0; i < m; i++){
scanf("%d %d %d", &x,&y,&weight);
cost[x][y] = weight;
cost[y][x] = weight;
}
}
void Dijsktra(int n)
{
/*
Fill in your code here...
calculate the distance from node 0 to all other nodes.
*/
int i;
int S[n];
S[0] = 1;
int all_visited = 0;
for(i=1;i<n;i++){
S[i] = -1;
}
for(i=0;i<n;i++){
distance[i] = cost[0][i];
}
while(all_visited != 1){
int temp = MAX_DIS;
int pos = -1;
for(i=1;i<n;i++){
if(S[i] == -1 && cost[0][i] <= temp){
temp = cost[0][i];
pos = i;
}
}
S[pos] = 1;
for(i=0;i<n;i++){
if(S[i] == -1)
break;
}
if(i==n)
all_visited = 1;
for(i=1; i<n; i++){
distance[i] = (int)fmin(distance[i], distance[pos] + cost[pos][i]);
}
}
}
int main()
{
int m,n;
printf("Input the number of nodes:\n");
scanf("%d",&n);
printf("Input the number of edges:\n");
scanf("%d",&m);
printf("Input these edges:\n");
initial(m,n);
Dijsktra(n);
for(int i=0;i<n;i++)
printf("%d ",distance[i]);
return 0;
}
#包括
#包括
#包括
#定义最大节点数100
#定义MAX_DIS 9999
整数成本[最大节点][最大节点];
int距离[MAX_节点];
无效首字母(整数m,整数n);
void Dijkstra(int n);
无效首字母(整数m,整数n)
{
/*
让用户输入所有边及其权重并初始化成本[]。
请注意,如果(x,y)之间没有边,则设置cost[x][y]=MAX\u DIS
和cost[a][b]=无向图的cost[b][a]。
在这里填写您的代码。。。
*/
int i,j;
对于(i=0;i在这个循环中使用break
语句
for(i=1;i<n;i++){
if(S[i] == -1 && cost[0][i] <= temp){
temp = cost[0][i];
pos = i;
break; //here
}
}
用于(i=1;我请共享失败的测试结果的输入、预期输出和实际输出:不要使用全局变量决定一种语言,而不是C和C++。通过自动压痕器运行代码,使其始终保持格式。它不仅吸引读者,而且还帮助您更容易地发现错误。一般而言,您应该提取一个在你的问题中包括输入(除非你能硬编码)、预期输出和实际输出。顺便说一句:名字是Dijkstra,不是Dijsktra!@4386427我已经按照你在问题中的要求添加了输出。现在请看一下。