Daa 08
Daa 08
1. Aim:
Develop a program and analyze complexity to find shortest paths in a graph with
positive edge weights using Dijkstra‟s algorithm.
2. Objective
Code and analyze to find shortest paths in graph with positive edge weights using
Dijkstra‟s
3. Algorithm
1. Initialize an adjacency matrix for node connections and set all distances to
infinity (INF).
2. Input number of vertices and edges, then input each edge's vertices and weight.
3. Set the initial distance from the source node to itself as zero.
4. Use a priority queue to manage and retrieve the node with the shortest distance
not yet visited.
5. For each node processed, update the distances to its adjacent nodes if a shorter
path is found.
6. Mark each node as visited once it's processed to prevent reprocessing.
7. Output the shortest distances from source node to all other nodes in the graph.
4. Implemetation/Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
// Read edges
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
adj[u][v] = {1, w}; // Indicate connection and weight
adj[v][u] = {1, w}; // Handle undirected graphs
}
int source;
cin >> source;
while (!pq.empty()) {
pair<long long, int> current = pq.top();
pq.pop();
int u = current.second;
if (visited[u]) {
continue; // Skip if already visited
}
visited[u] = true;
return 0;
}
Output:
5. Time Complexity : O( n2+ m + nlog n)
7. Learning Outcomes:-
1. Understand the implementation of Dijkstra's algorithm using adjacency
matrices.
2. Learn how to use priority queues to manage processing order of nodes based on
distance.
3. Recognize effect of node visitation state in preventing cycles and redundant
processing.
4. Gain experience in handling large constant values for initializations and
comparisons in graph algorithms.