DAA Worksheet-3.2 20BCS7611
DAA Worksheet-3.2 20BCS7611
------------------------------------------------------------------------------------------------------------------------------------
1. Aim/Overview of the practical:
Code and analyze to find the shortest paths in a graph with positive edge weights
using Dijkstra’s algorithm.
3. Algorithm/Flowchart :
1) First of all, we will mark all vertex as unvisited vertex
2) Then, we will mark the source vertex as 0 and all other vertices as infinity
3) Consider source vertex as current vertex
4) Calculate the path length of all the neighboring vertex from the current vertex by
adding the weight of the edge in the current vertex
5) Now, if the new path length is smaller than the previous path length then replace it
otherwise ignore it
6) Mark the current vertex as visited after visiting the neighbor vertex of the current
vertex
7) Select the vertex with the smallest path length as the new current vertex and go
back to step 4.
8) Repeat this process until all the vertex are marked as visited.
4.Steps for experiment/practical/Code:
#include <iostream>
using namespace std;
#include <limits.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
bool sptSet[V];
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}