Dijkstra只适用于非负权图(因为每循环一步就直接把未标号点集中路径最短的点标号,这样的话如果有负权图,是完全可能在下一步循环中使这条路径变短的),路径的话可以在循环中记录每个结点的前驱结点,最后用栈输出出来。
#include <iostream>
#include <stack>
using namespace std;
#define N 1000
int dist[N], flag[N], path[N];
int A[N][N];
stack<int> Q;
void show_path(int m);
int main()
{
int n, cnt, k, temp;
cnt = 1;
cout << "Please enter the number of vertex in your graph:" << endl;
cin >> n;
cout << "Please enter your graph as a matrix:" << endl;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> A[i][j];
for (int i = 1; i <= n; i++)
{
dist[i] = A[1][i];
path[i] = 1;
}
flag[1] = 1; k = 1;
while (cnt < n)
{
for (int i = 1; i <= n; i++)
{
if (flag[i] == 1)
continue;
else
{
if (dist[i] > dist[k] + A[k][i])
{
dist[i] = dist[k] + A[k][i];
path[i] = k;
}
}
}
int min = 10000;
for (int i = 1; i <= n; i++)
{
if (flag[i] == 0 && min > dist[i])
{
min = dist[i];
temp = i;
}
}
flag[temp] = 1;
k = temp;
cnt++;
}
for (int i = 1; i <= n; i++)
{
cout << "1->" << i << " length: " << dist[i] << " path: ";
show_path(i);
}
system("pause");
return 0;
}
void show_path(int m)
{
int k = m;
while (!Q.empty())
Q.pop();
while (k != 1)
{
Q.push(k);
k = path[k];
}
Q.push(1);
while (!Q.empty())
{
cout << Q.top() << " ";
Q.pop();
}
cout << endl;
return;
}