0%

Dijkstra算法找单源最短路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//Dijkstra寻找最短路径(广度优先思想)
//用邻接矩阵实现图的存储,为简化问题,省去对图的定义
//单源最短路径问题:给定源顶点s,求它到其他任意顶点(目的顶点)的最短路径

#include<iostream>
using namespace std;
int Max = 100;
void djstr(int** a, int v, int e)
{
int* p = new int[v];
//p[i]:最短路径中顶点i的前驱顶点,
//从终点开始,逆向即可获取路径
int* d = new int[v];
//当前最短路径长度

int s = 0;
bool* label = new bool[v];
for (int i = 0; i < v; i++)
label[i] = false;

for (int i = 0; i < v; i++)
if (a[0][i] > 0)
{
p[i] = 0;
d[i] = a[0][i];
}
else
{
p[i] = -1;
d[i] = Max;
}
label[0] = true;
while (s < v)
{
int index=0, min=d[0];
for(int i=0;i<v;i++)
if (!label[i]&&d[i] < min)
{
min = d[i];
index = i;
}
++s; label[index] = true;
for (int i = 0; i < v; i++)
{
if (a[index][i] + d[index] < d[i])
{
d[i] = a[index][i] + d[index];
p[i] = index;
}
}
}
d[0] = 0;
for (int i = 0; i < v; i++)
cout << d[i] << " ";
cout << endl;
for (int i = 0; i < v; i++)
cout << p[i]+1 << " ";
}
int main()
{

int v = 5;
int e = 7;
int b[5][5] = {
{ 0,4,2,Max,8 },
{ Max,0,Max,4,5 },
{ Max,Max,0,1,Max },
{ Max,Max,Max,0,3 },
{ Max,Max,Max,Max,0 } };
int** a = new int*[v];
for (int i = 0; i < v; i++)
{
a[i] = new int[v];
for (int j = 0; j < v; j++)
a[i][j] = b[i][j];
}
djstr(a, v, e);
system("pause");
return 0;
}