代码
#include<iostream>
using namespace std;
const int INF =0x3f3f3f3f;
int a[7][7]={
//A B C D E F G
/*A*/{INF,12,INF,INF,INF,16,14},
/*B*/{12,INF,10,INF,INF,7,INF},
/*C*/{INF,10,INF,3,5,6,INF},
/*D*/{INF,INF,3,INF,4,INF,INF},
/*E*/{INF,INF,5,4,INF,2,8},
/*F*/{16,7,6,INF,2,INF,9},
/*G*/{14,INF,INF,INF,8,9,INF}
};
int vis[7], s[7], u[7];
void Dijkstra(int index)
{
vis[index] = 1;
for (int i = 0; i < 7; i++)
{
u[i] = a[index][i];
}
int min_cur = index;
int count = 6;
while (count--)
{
int minx = INF;
for (int i = 0; i < 7; i++)
{
if (!vis[i] && u[i] < minx)
{
minx = u[i];
min_cur = i;
}
}
//求出来的最小值一定是当前min_cur离目标的最短路径
vis[min_cur] = 1;
s[min_cur] = minx;
for (int i = 0; i < 7; i++)
{
int tmp = a[i][min_cur] == INF ? INF : minx+a[i][min_cur];
if (!vis[i] && tmp < u[i])
{
u[i] = tmp; //更新U集合
}
}
}
}
int main()
{
Dijkstra(3);
for (int i = 0; i < 7; i++)
cout << "D到" << char(i + 'A') << "的距离为" << s[i] << endl;
return 0;
}