4. Dijkstra's
// Adjacency List
vector<vector<pair<int,int>>> adj(n + 1);
// Build Graph
for (auto &edge : times) {
int u = edge[0];
int v = edge[1];
int wt = edge[2];
adj[u].push_back({v, wt});
}
// Min Heap
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
greater<pair<int,int>>
> pq;
// Distance Array
vector<int> dist(V, INT_MAX);
dist[src] = 0;
// parent[src] = src; // If you also want the path
pq.push({0, src});
while (!pq.empty()) {
auto [distance, node] = pq.top();
pq.pop();
// Skip outdated entries
if (distance > dist[node])
continue;
// Explore neighbors
for (auto [neighbor, weight] : adj[node]) {
// Relax the edge
if (dist[node] + weight < dist[neighbor]) {
dist[neighbor] = dist[node] + weight;
// Store parent
// parent[neighbor] = node;
pq.push({dist[neighbor], neighbor});
}
}
}
// dist[i] contains shortest distance from src to i
To get the path
vector<int> path;
if (dist[dest] == INT_MAX) {
cout << "No Path";
}
else {
int node = dest;
while (node != parent[node]) {
path.push_back(node);
node = parent[node];
}
path.push_back(src);
reverse(path.begin(), path.end());
}