-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.cpp
More file actions
71 lines (56 loc) · 1.82 KB
/
dijkstra.cpp
File metadata and controls
71 lines (56 loc) · 1.82 KB
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
#include <cmath>
#include <algorithm>
#include <queue>
#include <stdio.h>
#include "dijkstra.h"
typedef std::pair<double, int> vertex_distance;
int dijkstra(Adjacency *adjacency, int n, int s, double distances[], int nodes[])
{
static std::priority_queue<vertex_distance, std::vector<vertex_distance>, std::greater<vertex_distance> > my_min_heap;
bool *visited = new bool[n];
std::vector<vertex_distance> to_sort;
std::vector<vertex_distance>::iterator it;
int i;
int current = 0;
int reachable = 0;
for (i = 0; i < n; ++i)
{
visited[i] = false;
distances[i] = +INFINITY;
}
distances[s] = 0.0;
my_min_heap.push(std::make_pair(distances[s], s));
while (!my_min_heap.empty())
{
vertex_distance top = my_min_heap.top();
int u = top.second;
double d = top.first;
int *it;
my_min_heap.pop();
if (d <= distances[u])
{
++reachable;
for (i = adjacency->shifts[u]; i != adjacency->shifts[u + 1]; ++i)
{
int v = adjacency->edges[i];
double cost = adjacency->weights[i];
if (distances[u] + cost < distances[v])
{
distances[v] = distances[u] + cost;
my_min_heap.push(std::make_pair(distances[v], v));
}
}
}
}
for (i = 0; i < n; ++i)
to_sort.push_back(std::make_pair(distances[i], i));
std::sort(to_sort.begin(), to_sort.end());
for (it = to_sort.begin(), current = 0; it != to_sort.end(); ++it, ++current)
{
nodes[current] = it->second;
distances[current] = it->first;
//printf("node %d distance %f\n", nodes[i], distances[nodes[i]]);
}
delete [] visited;
return reachable;
}