Bellman-Ford算法适用于不含负环路的图,比Dijkstra适用范围广。但是时间复杂度为O(n^3)。
#include <iostream>
#include <math.h>
#include <stack>
using namespace std;
#define N = 1000
stack<int> Q;
int path[N];
int dist[N][N];
int A[N][N];
void show_path(int k);
int main()
{
int ppath[N];
int n, t, min, front, node;
t = 0;
cout << "Please enter the number of vertex in your graph:";
cout << endl;
cin >> n;
cout << "Please enter your graph as a matrix:";
cout << endl;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> A[i][j];
path[1] = 0; dist[1][0] = 0;
for (int i = 2; i <= n; i++)
for (int j = 0; j <= n; j++)
dist[i][j] = 1000000;
while (t < n)
{
for (int i = 2; i <= n; i++)
{
min = dist[1][t]+A[1][i]; front = 1;
for (int j = 2; j <= n; j++)
{
if (min > dist[j][t] + A[j][i])
{
min = dist[j][t] + A[j][i];
front = j;
}
}
dist[i][t+1] = min;
if (min < dist[i][t])
path[i] = front;
}
t++;
}
//cout << path[1] << endl;
for (int i = 1; i <= n; i++)
{
cout << "node" << i << "; " << dist[i][n] << endl;
show_path(i);
}
system("pause");
return 0;
}
void show_path(int k)
{
int h = k;
//stack<int> Q;
while (!Q.empty())
Q.pop();
while (h)
{
Q.push(h);
h = path[h];
}
while (!Q.empty())
{
cout << Q.top() << " ";
Q.pop();
}
cout << endl;
return;
}