Dijkstra算法求解最短距离问题

6 8 0  //6个顶点八条边
0 1 1//0到1的边权为1
0 3 4
0 4 4
1 3 2
2 5 1
3 2 2
3 4 3

4 5 3


#include
#include
#include
using namespace std;
const int MAXV = 1000;
const int INF = 1000000000;
int n, m,s,G[MAXV][MAXV];
int d[MAXV];
bool vis[MAXV] = {false};
void Dijkstra(int s)
{
fill(d,d+MAXV,INF);
d[s] = 0;
for (int i=0;i{
int u = -1, MIN = INF;
for (int j=0;j{
if (vis[j]==false&&d[j]{
u = j;
MIN = d[j];
}
}
if (u == -1)
{
return;
}
vis[u] = true;//标记已访问
for (int v=0;v{
if (vis[v]==false&&G[u][v]!=INF&&d[u]+G[u][v]{
d[v] = d[u] + G[u][v];//优化d[v]
}
}


}
}


int main()
{
int u, v,w;
cin >> n >> m >> s;
fill(G[0],G[0]+MAXV*MAXV,INF);//初始化图 
for (int i = 0; i < m; i++)
{
cin >> u >> v >> w;
G[u][v] = w;
}
Dijkstra(s);
for (int i=0;i{
cout << d[i]<< " ";
}


system("pause");
}





你可能感兴趣的:(数据结构和算法)