Skip to content

Commit

Permalink
Create johnson.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
paliwalsamarth authored Oct 27, 2020
1 parent dc14603 commit 01ef445
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions CPP/Johnson’s Algorithm/johnson.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include<iostream>
#define INF 9999
using namespace std;
int min(int a, int b);
int cost[10][10], adj[10][10];
inline int min(int a, int b){
return (a<b)?a:b;
}
main() {
int vert, edge, i, j, k, c;
cout << "Enter no of vertices: ";
cin >> vert;
cout << "Enter no of edges: ";
cin >> edge;
cout << "Enter the EDGE Costs:\n";
for (k = 1; k <= edge; k++) { //take the input and store it into adj and cost matrix
cin >> i >> j >> c;
adj[i][j] = cost[i][j] = c;
}
for (i = 1; i <= vert; i++)
for (j = 1; j <= vert; j++) {
if (adj[i][j] == 0 && i != j)
adj[i][j] = INF; //if there is no edge, put infinity
}
for (k = 1; k <= vert; k++)
for (i = 1; i <= vert; i++)
for (j = 1; j <= vert; j++)
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]); //find minimum path from i to j through k
cout << "Resultant adj matrix\n";
for (i = 1; i <= vert; i++) {
for (j = 1; j <= vert; j++) {
if (adj[i][j] != INF)
cout << adj[i][j] << " ";
}
cout << "\n";
}
}

0 comments on commit 01ef445

Please sign in to comment.