forked from Synergise-IIT-Bhubaneswar/Beta-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented Warshall Algorithm In C++
- Loading branch information
1 parent
82c4fb7
commit a1cd111
Showing
1 changed file
with
84 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
#include <iostream> | ||
#include <climits> | ||
#include <iomanip> | ||
using namespace std; | ||
#define N 4 | ||
#define M INT_MAX | ||
void printpath(int path[][N], int v, int u) | ||
{ | ||
if (path[v][u] == v) | ||
return; | ||
|
||
printpath(path, v, path[v][u]); | ||
cout << path[v][u] << " "; | ||
} | ||
void solution(int cost[N][N], int path[N][N]) | ||
{ | ||
for (int v = 0; v < N; v++) | ||
{ | ||
for (int u = 0; u < N; u++) | ||
{ | ||
if (u != v && path[v][u] != -1) | ||
{ | ||
cout << "Shortest Path from " << v << " -> " << u << " is (" | ||
<< v << " "; | ||
printpath(path, v, u); | ||
cout << u << ")" << endl; | ||
} | ||
} | ||
} | ||
} | ||
|
||
void WarshallAlgo(int adjMatrix[][N]) | ||
{ | ||
int cost[N][N], path[N][N]; | ||
for (int v = 0; v < N; v++) | ||
{ | ||
for (int u = 0; u < N; u++) | ||
{ | ||
cost[v][u] = adjMatrix[v][u]; | ||
|
||
if (v == u) | ||
path[v][u] = 0; | ||
else if (cost[v][u] != INT_MAX) | ||
path[v][u] = v; | ||
else | ||
path[v][u] = -1; | ||
} | ||
} | ||
|
||
for (int k = 0; k < N; k++) | ||
{ | ||
for (int v = 0; v < N; v++) | ||
{ | ||
for (int u = 0; u < N; u++) | ||
{ | ||
if (cost[v][k] != INT_MAX && cost[k][u] != INT_MAX && cost[v][k] + cost[k][u] < cost[v][u]) | ||
{ | ||
cost[v][u] = cost[v][k] + cost[k][u]; | ||
path[v][u] = path[k][u]; | ||
} | ||
} | ||
|
||
if (cost[v][v] < 0) | ||
{ | ||
cout << "Negative Weight Cycle Found!!"; | ||
return; | ||
} | ||
} | ||
} | ||
solution(cost, path); | ||
} | ||
|
||
int main() | ||
{ | ||
int adjMatrix[N][N] = | ||
{ | ||
{0, M, -2, M}, | ||
{4, 0, 3, M}, | ||
{M, M, 0, 2}, | ||
{M, -1, M, 0}}; | ||
WarshallAlgo(adjMatrix); | ||
|
||
return 0; | ||
} |