Lab 5 (Fouzia)
Lab 5 (Fouzia)
Single Source Shortest Path: The Single Source Shortest Path problem aims to find
the shortest path from a given source vertex to all other vertices in a weighted graph.
Dijkstra's Algorithm solves this problem for graphs with non-negative edge weights. It
starts from the source vertex, initializes distances to all other vertices as infinite, and sets
the source's distance to zero. The algorithm repeatedly selects the vertex with the
smallest known distance, updates the distances of its neighboring vertices, and marks it
as processed. This process continues until all vertices are processed, ensuring that the
shortest path from the source to every other vertex is found.
Dijkstra’s Algorithm
For each edge (u, v) E, assume w(u, v) ≥ 0, maintain a set S of vertices whose
final shortest path weights have been determined. Repeatedly select u V − S with
minimum shortest path estimate, add u to S, relax all edges out of u.
Pseudo-code
Dijkstra (G, W, s) //uses priority queue Q
Initialize (G, s)
S←φ
Q ← V [G] //Insert into Q
while Q = φ
do u ← EXTRACT-MIN(Q) //deletes u from Q
S = S ∪ {u}
for each vertex v Adj[u]
do RELAX (u, v, w) ← this is an implicit DECREASE KEY operation
Code:
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <limits>
#include <functional>
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) continue;
visited[u] = true;
// Relaxation step
if (!visited[v] && dist[v] > dist[u] + weight) {
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
}
}
}
int main() {
int V = 9;
vector<vector<iPair>> graph(V);
graph[0].push_back(make_pair(1, 4));
graph[0].push_back(make_pair(7, 8));
graph[1].push_back(make_pair(0, 4));
graph[1].push_back(make_pair(2, 8));
graph[1].push_back(make_pair(7, 11));
graph[2].push_back(make_pair(1, 8));
graph[2].push_back(make_pair(3, 7));
graph[2].push_back(make_pair(5, 4));
graph[2].push_back(make_pair(8, 2));
graph[3].push_back(make_pair(2, 7));
graph[3].push_back(make_pair(4, 9));
graph[3].push_back(make_pair(5, 14));
graph[4].push_back(make_pair(3, 9));
graph[4].push_back(make_pair(5, 10));
graph[5].push_back(make_pair(2, 4));
graph[5].push_back(make_pair(3, 14));
graph[5].push_back(make_pair(4, 10));
graph[5].push_back(make_pair(6, 2));
graph[6].push_back(make_pair(5, 2));
graph[6].push_back(make_pair(7, 1));
graph[6].push_back(make_pair(8, 6));
graph[7].push_back(make_pair(0, 8));
graph[7].push_back(make_pair(1, 11));
graph[7].push_back(make_pair(6, 1));
graph[7].push_back(make_pair(8, 7));
graph[8].push_back(make_pair(2, 2));
graph[8].push_back(make_pair(6, 6));
graph[8].push_back(make_pair(7, 7));
dijkstra(graph, 0);
return 0;
}