经典图论算法。用于计算两点之间的最短距离。也可以用于计算某一点 (source)到其他所有点的最短距离。
伪代码
Dijstra (graph, n, src)
initialize dist := [...inf...] with dist[src] = 0
initialize priority queue pq; add (0, src) to pq
while pq is not emtpy
u = pq.top()[1]
pq.pop()
for neighbor, weight in graph[u]
if dist[neighbor] > dist[u] + weight
dist[neighbor] = dist[u] + weight
pq.push((dist[neighbor], neighbor))
return dist
cpp 代码
vector<int> dijstra(map<int, vector<pair<int, int>> & graph, int n, int src) {
// Create a priority queue to store vertices that
// are being preprocessed. This is weird syntax in C++.
// Refer below link for details of this syntax
// http://geeksquiz.com/implement-min-heap-using-stl/
priority_queue< pair<int, int> > pq;
// Create a vector for distances and initialize all
// distances as infinite (INF)
vector<int> dist(n+1, INT_MAX); // dist[0] is useless
// Insert source itself in priority queue and initialize
// its distance as 0.
pq.push(make_pair(0, src));
dist[src] = 0;
/* Looping till priority queue becomes empty (or all
distances are not finalized) */
while (!pq.empty())
{
// The first vertex in pair is the minimum distance
// vertex, extract it from priority queue.
// vertex label is stored in second of pair (it
// has to be done this way to keep the vertices
// sorted distance (distance must be first item
// in pair)
int u = pq.top().second;
pq.pop();
// Get all adjacent of u.
for (auto x : graph[u])
{
// Get vertex label and weight of current adjacent
// of u.
int v = x.first;
int weight = x.second;
// If there is shorted path to v through u.
if (dist[v] > dist[u] + weight)
{
// Updating distance of v
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
}
}
}
return dist;