Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

#include <iostream>

using namespace std;

int main()
{
// initialize variables
int verts, i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, sum = 0, tsum1 = 0, tsum2 = 0, temp1 = 0, temp2 = 0;

// take in number of vertices and initialize arrays


cin >> verts;
int omat[verts][verts];
int fmat[verts][verts];

// take in values of weighted edges for matrix


for (i = 0; i < verts; i++)
{
for (j = 0; j < verts; j++)
{
cin >> temp1;
omat[i][j] = temp1;
fmat[i][j] = temp1;
}
}

// Floyd's algorithm with 3 nested loops


for (k = 0; k < verts; k++)
{
for (i = 0; i < verts; i++)
{
for (j = 0; j < verts; j++)
{

// make numbers very large if infinite weight


if (fmat[i][k] < 0)
{
tsum1 = 999999;
}
else if (fmat[k][j] < 0)
{
tsum1 = 999999;
}
else
{
tsum1 = fmat[i][k] + fmat[k][j];
}
if (fmat[i][j] < 0)
{
tsum2 = 99999;
}
else
{
tsum2 = fmat[i][j];
}

// check if looping to self


if (i == k)
{
// do nothing
}
else if (j == k)
{
// do nothing
}

// change weight and change if less


else if (tsum1 < tsum2)
{
fmat[i][j] = tsum1;
}
}
}
}

// output finished matrix


for (i = 0; i < verts; i++)
{
for (j = 0; j < verts; j++)
{
if (j == 0)
{
cout << fmat[i][j];
}
else
{
cout << " " << fmat[i][j];
}
}
cout << endl;
}

return 0;
}

You might also like