Harshit DAA 3.2
Harshit DAA 3.2
Aim:
Develop a program and analyze complexity to find shortest paths in a graph with positive
edge weights using Dijkstra’s algorithm.
Objective:
Code and analyze to find shortest paths in a graph with positive edge weights using
Dijkstra’s Algorithm.
Input/Apparatus Used:
Procedure/Algorithm:
Step-1: Create a graph represented by the adjacency matrix 'adj[maxv][maxv]' with 'V'
vertices.
Step-2: Initialize an array 'dist[maxv]' with size 'V' to store the shortest distances from
the source vertex. Set all elements to infinity (or a sufficiently large value), except for
the source vertex, which is set to 0.
Step-3: Create a priority queue (min-heap) to store vertices to be processed. Initialize
Sample Code:
#include <bits/stdc++.h>
#include <queue>
#include <climits>
struct Edge {
struct Compare {
bool operator()(const Edge &a, const Edge &b) {
return a.weight > b.weight;
}
};
int V;
int adj[maxv][maxv];
int dist[maxv];
while (!pq.empty()) {
int u = pq.top().to;
int weight = pq.top().weight;
pq.pop();
if (weight > dist[u]) continue;
for (int v = 0; v < V; ++v) {
if (adj[u][v] && dist[v] > dist[u] + adj[u][v]) {
dist[v] = dist[u] + adj[u][v];
pq.push({v, dist[v]});
}
int main() {
V = 5;
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
adj[i][j] = 0;
}
}
adj[0][1] = 4;
adj[0][2] = 8;
adj[1][2] = 7;
adj[1][3] = 9;
adj[2][4] = 5;
adj[3][4] = 6;
int source = 0;
dijkstra(source);
return 0;
}
Space Complexity:
The space complexity is O(V^2) for the adjacency matrix because it uses a 2D array
to represent the graph, which has V * V elements.
Learning Outcomes:
I learned about Dijkstra’s Algorithm.
I learned to find the shortest path in a graph with positive edge weights using
Dijkstra’s Algorithm.
I learned about the time and space complexity of Dijkstra’s Algorithm.
I learned about its implementation and uses in path finding.