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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
| #include <iostream>
#include "graph.hpp"
#include <climits>
#include <queue>
using namespace std;
/**
* 用于记录图结点数据
* id 结点id
* dist 源结点到当前结点的最短距离
* prev 最短路径的前一个结点
* processed 是否遍历过
**/
struct node {
int id;
int dist;
int prev;
bool processed;
node():dist(INT_MAX),prev(-1),processed(false){
}
};
/**
* 用于比较距离大小的仿函数
**/
struct compare_node {
bool operator()(node& a,node &b){
return a.dist > b.dist;
}
};
/**
* Dijkstra算法
* g 操作的图
* source 源结点
**/
vector<node> Dijkstra(Graph &g,int source){
//获取图结点个数
int node_count = (int)g.ad_vector.size();
//将遍历每个结点的结果存放在nodes容器
vector<node> nodes(node_count);
for (int i=0; i< node_count; i++) {
nodes[i].id = i;
}
nodes[source].dist = 0;
//优先队列,dist小的先出队
priority_queue<node,vector<node>,compare_node> node_pq;
node_pq.push(nodes[source]);
while (!node_pq.empty()) {
node current_node = node_pq.top();
node_pq.pop();
if (current_node.processed) {
continue;
}else{
list<edge_node> edge_nodes = g.ad_vector[current_node.id];
for (auto pos = edge_nodes.begin(); pos!=edge_nodes.end(); pos++) {
node& dest_node = nodes[pos->dest_id];
if (current_node.dist+pos->weight<dest_node.dist) {
dest_node.dist = current_node.dist+pos->weight;
dest_node.prev = current_node.id;
node_pq.push(dest_node);
}
}
current_node.processed = true;
}
}
return nodes;
}
void print_path(vector<node>& nodes,int node_id){
if (nodes[node_id].prev==-1) {
cout<<"path: "<<node_id;
}else{
print_path(nodes,nodes[node_id].prev);
cout<< "->" << node_id;
}
}
int main(int argc, const char * argv[]) {
Graph g(7);
g.add_edge(0, 1, 2);
g.add_edge(0, 3, 9);
g.add_edge(0, 4, 6);
g.add_edge(1, 2, 1);
g.add_edge(1, 4, 3);
g.add_edge(2, 4, 1);
g.add_edge(2, 6, 6);
g.add_edge(4, 3, 2);
g.add_edge(4, 5, 9);
g.add_edge(5, 6, 5);
vector<node> result = Dijkstra(g, 0);
for(int i = 0; i < result.size(); i++){
cout << "Print path and dist for node:" << result[i].id << endl;
print_path(result, result[i].id);
cout << endl << "Dist:" << result[i].dist << endl;
}
return 0;
}
|