模板一:
const int maxn = 10001;
void Dijkstra(int n, int dist[maxn], int map[maxn][maxn], int pre[maxn], int s)
{
int i, j, k;
int min;
bool p[maxn];
for (i = 1; i <= n; i++)
{
p[i] = false;
if (i != s)
{
dist[i] = map[s][i];
pre[i] = s;
}
}
dist[s] = 0;
p[s] = true;
for (i = 1; i <= n - 1; i++)
{
min = INT_MAX;
k = 0;
for (j = 1; j <= n; j++)
{
if (!p[j] && dist[j] < min)
{
min = dist[j];
k = j;
}
}
}
if (k == 0) return;
p[k] = true;
for (j = 1; j <= n; j++)
{
if (!p[j] && map[k][j] != INT_MAX && dist[j] > dist[k] + map[k][j])
{
dist[j] = dist[k] + map[k][j];
pre[j] = k;
}
}
}
模板二:
#include<iostream>
#define max 50
#define INF 0x7fffffff
using namespace std;
int matrix[max][max];
void Dijkstra(int out[], int N, int V0)
{
int i;
int visited[max] = { 0 };
int last_visited = 0;
for (i = 0; i < N; i++)
{
out[i] = INF;
}
visited[V0] = 1;
out[V0] = 0;
for (i = 0; i < N - 1; i++)
{
for (int j = 0; j < N; j++)
{
if (visited[j] == 0)
{
if (matrix[V0][j] != 0)
{
int dis = matrix[V0][j] + last_visited;
if (dis < out[j])
{
out[j] = dis;
}
}
}
}
int minIdex = 0;
while (visited[minIdex] == 1)
minIdex++;
for (int j = minIdex; j < N; j++)
{
if (visited[j] == 0 && out[j] < out[minIdex])
{
minIdex = j;
}
}
visited[minIdex] = 1;
last_visited = out[minIdex];
V0 = minIdex;
}
}
int main()
{
int n;
int result[max];
cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
}
Dijkstra(result,n,0);
for (int i = 0; i < n; i++)
{
if (result[i] == INF)
cout << "INF"<<" ";
else
cout << result[i] << " ";
}
system("pause");
}
/*8
0 20 0 80 0 0 90 0
0 0 0 0 0 10 0 0
0 0 0 10 0 50 0 20
0 0 10 0 0 0 20 0
0 50 0 0 0 0 30 0
0 0 10 40 0 0 0 0
20 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0*/