Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing code for dijkstra (not in presentation) #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions 17-single-source-shortest-path/src/dijkstra.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <queue>
#include <utility>
#include <vector>
using namespace std;

vector<int> dijkstra(const vector<vector<pair<int, int>>>& graph, int start) {
// graph contains pairs of (node, weight) for edges, as an adjacency list

// return the shortest distances to every other node
// -1 indicates infinity
vector<int> dist(graph.size(), -1);

// Add vector<int> parent here for path reconstruction

// We use std::greater to have the smallest cost first, since by default priority_queue is a max heap
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;

q.push(make_pair(0, start));

while (!q.empty()) {
pair<int, int> tmp = q.top();
q.pop();
int cost = tmp.first;
int node = tmp.second;

// Avoid too much work
if (cost > dist[node]) continue;

// You can stop early here if you have a target instead of calculating to every other node

for (pair<int, int> neigh : graph[node]) {
int newnode = neigh.first;
int newcost = cost + neigh.second;
if (dist[newnode] == -1 || newcost < dist[newnode]) {
// update parent[newnode] if doing path reconstruction

dist[newnode] = newcost;
q.push(make_pair(newcost, newnode));
}
}
}

return dist;
}