Skip to content

Commit

Permalink
Implemented Warshall Algorithm In C++
Browse files Browse the repository at this point in the history
  • Loading branch information
vidit21srivastava committed Dec 27, 2021
1 parent 82c4fb7 commit a1cd111
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions c++/graph/warshall.cpp
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;
}

0 comments on commit a1cd111

Please sign in to comment.