This C++ program displays the shortest path traversal from a particular node to every other node present inside the graph relative to the former node.
Here is the source code of the C++ program of the Djikstra’s Algoritm of finding shortest paths from the first node in graph to every other node with the shortest path length displayed beside each pair of vertices.This C++ program is successfully compiled and run on DevCpp,a C++ compiler.The program output is given below.
/*
* C++ Program to find SSSP(Single Source Shortest Path)
* in DAG(Directed Acyclic Graphs)
*/
#include <iostream>
#include <conio.h>
using namespace std;
#define INFINITY 999
struct node
{
int from;
}p[7];
int c = 0;
void djikstras(int *a,int b[][7],int *dv)
{
int i = 0,j,min,temp;
a[i] = 1;
dv[i] = 0;
p[i].from = 0;
for (i = 0; i < 7;i++)
{
if (b[0][i] == 0)
{
continue;
}
else
{
dv[i] = b[0][i];
p[i].from = 0;
}
}
while (c < 6)
{
min = INFINITY;
for (i = 0; i < 7; i++)
{
if (min <= dv[i] || dv[i] == 0 || a[i] == 1)
{
continue;
}
else if (min > dv[i])
{
min = dv[i];
}
}
for (int k = 0; k < 7; k++)
{
if (min == dv[k])
{
temp = k;
break;
}
else
{
continue;
}
}
a[temp] = 1;
for (j = 0; j < 7; j++)
{
if (a[j] == 1 || b[temp][j] == 0)
{
continue;
}
else if (a[j] != 1)
{
if (dv[j] > (dv[temp] + b[temp][j]))
{
dv[j] = dv[temp] + b[temp][j];
p[i].from = temp;
}
}
}
c++;
}
for (int i = 0; i < 7; i++)
{
cout<<"from node "<<p[i].from<<" cost is:"<<dv[i]<<endl;
}
}
int main()
{
int a[7];
int dv[7];
for(int k = 0; k < 7; k++)
{
dv[k] = INFINITY;
}
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for (int i = 0;i < 7;i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for(int j = 0;j < 7;j++)
{
cin>>b[i][j];
}
}
djikstras(a,b,dv);
getch();
}
Output enter values for 1 row 0 3 6 0 0 0 0 enter values for 2 row 3 0 2 4 0 0 0 enter values for 3 row 6 2 0 1 4 2 0 enter values for 4 row 0 4 1 0 2 0 4 enter values for 5 row 0 0 4 2 0 2 1 enter values for 6 row 0 0 2 0 2 0 1 enter values for 7 row 0 0 0 4 1 1 0 from node 0 to node 0 minimum cost is:0 from node 0 to node 1 minimum cost is:3 from node 0 to node 2 minimum cost is:5 from node 0 to node 3 minimum cost is:6 from node 0 to node 4 minimum cost is:8 from node 0 to node 5 minimum cost is:7 from node 0 to node 6 minimum cost is:8
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at other example programs on Linked List, go to Linked List. If you wish to look at programming examples on all topics, go to C Programming Examples.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Check Programming Books
- Check Computer Science Books
- Apply for C++ Internship
- Check C++ Books