ria exp 6
ria exp 6
UID: 2023300242
Experiment No. 6
Program 1
Problem: 1. To find the shortest path from a single source to all other nodes in a
weighted graph using Dijkstra’s algorithm
2. Calculate time complexity for it.
Algorithm :
#define V 5
return minindex;
}
dist[start] = 0;
visited[u] = 1;
int main() {
int graph[V][V] = {
{0, 0, 8, 0, 2},
{0, 0, 0, 2, 7},
{8, 0, 0, 1, 5},
{0, 2, 1, 0, 3},
{2, 7, 5, 3, 0}
};
dj(graph, 0);
return 0;
}
Example 1
Output:
Observations:
The time complexity of Dijkstra’s algorithm (using an array for visited nodes) is primarily
determined by two key operations: finding the minimum-distance unvisited node and relaxing
edges. In each iteration, the algorithm searches for the unvisited node with the smallest known
distance, which takes O(V) time. Since this selection process repeats for V vertices, it contributes
O(V²) to the overall complexity. This approach is suitable for dense graphs where the number of
edges approaches V², but less efficient for sparse graphs compared to the priority queue-based
approach.
Program 2
Problem: 1. To find the shortest path from a single source to all other nodes in a
weighted graph using Bellman-Ford’s
2. Calculate time complexity for it.
#define V 6
#define E 8
struct Edge {
int src, dest, weight;
};
int main() {
BellmanFord(edges, 0);
return 0;
}
Example 1
Output:
Observations:
The time complexity of the Bellman-Ford algorithm is primarily influenced by two operations: edge
relaxation and negative cycle detection. The algorithm performs V - 1 iterations, where V is the
number of vertices, and in each iteration, it relaxes all E edges. Consequently, the overall time
complexity is O(V × E). While Bellman-Ford is well-suited for graphs with fewer edges and those
containing negative weights, it is less efficient than Dijkstra’s algorithm for dense graphs.
Conclusion:
From this experiment, I learned about the efficiency and applicability of Dijkstra’s and Bellman-Ford’s
algorithms for shortest path calculations. Dijkstra’s algorithm, with a time complexity of O(V²) when using
an array, is highly efficient for dense graphs but cannot handle negative weights. On the other hand,
Bellman-Ford, with a complexity of O(V × E), can accommodate negative weights and detect negative
cycles but is significantly slower for large graphs. The choice between these algorithms depends on the
graph’s structure—Dijkstra is preferable for non-negative weighted graphs, while Bellman-Ford is essential
when negative weights or cycle detection is required.