gpt4 book ai didi

C++ Dijkstra的算法程序,初始顶点问题和结果少一个顶点

转载 作者:行者123 更新时间:2023-11-30 03:20:39 25 4
gpt4 key购买 nike

我正在研究 Dijkstra 算法的 C++ 表示/实现,我在网上发现这个程序无法在 TurboC++ 上正确执行。有人知道解决方案吗?我也想知道为什么有最小值 31999 并且编码在移动模拟器上运行但拒绝在 PC TurboC++ 上运行

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
//using namespace std;
int shortest(int, int);
int cost[10][10], dist[20], i, j, n, k, m, S[20], v, totcost, path[20], p;
int main()
{
int c;
cout << "enter no of vertices";
cin >> n;
cout << "enter no of edges";
cin >> m;

cout << "\nenter\nEDGE Cost\n";
for (k = 1; k <= m; k++)
{
cin >> i >> j >> c;
cost[i][j] = c;
}

for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
if (cost[i][j] == 0)
cost[i][j] = 31999;

cout << "enter initial vertex";
cin >> v;
cout << v << "\n";
shortest(v, n);
}

int shortest(int v, int n)
{
int min;
for (i = 1; i <= n; i++)
{
S[i] = 0;
dist[i] = cost[v][i];
}
path[++p] = v;
S[v] = 1;
dist[v] = 0;
for (i = 2; i <= n - 1; i++)
{
k = -1;
min = 31999;
for (j = 1; j <= n; j++)
{
if (dist[j] < min && S[j] != 1)
{
min = dist[j];
k = j;
}
}

if (cost[v][k] <= dist[k])
p = 1;
path[++p] = k;

for (j = 1; j <= p; j++)
cout << path[j];
cout << "\n";
//cout <<k;
S[k] = 1;
for (j = 1; j <= n; j++)
if (cost[k][j] != 31999 && dist[j] >= dist[k] + cost[k][j] && S[j] != 1)
dist[j] = dist[k] + cost[k][j];
}
}

最佳答案

数组是从 0 开始的,所以从 1 到 <= n 的所有循环都是可疑的。

关于C++ Dijkstra的算法程序,初始顶点问题和结果少一个顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52716348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com