You are on page 1of 2

/*

* Title: hw6_2.cpp
* Abstract: Implements the Floyd algorithm to display all-pairs shortest paths
* Author: Trinidad Ramirez
* ID: 5555
* Date: 12/10/2021
*/

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

#define INFTY 1000000

// Prototype
void floydAlgorithm(int numOfVertices);

int main() {
int numOfVertices = 0;
cin >> numOfVertices;
floydAlgorithm(numOfVertices);
return 0;
}

void floydAlgorithm(int numOfVertices) {


int matrix[numOfVertices][numOfVertices],
graph[numOfVertices][numOfVertices],
node = 0;

// Get graph data from user. If -1 is entered, change it to INFTY


for (int i = 0; i < numOfVertices; i++) {
for (int j = 0; j < numOfVertices; j++) {
cin >> node;
if (node == -1) { node = INFTY; }
graph[i][j] = node;
}
}

for (int i = 0; i < numOfVertices; i++) {


for (int j = 0; j < numOfVertices; j++) {
matrix[i][j] = graph[i][j];
}
}
for (int i = 0; i < numOfVertices; i++) {
for (int j = 0; j < numOfVertices; j++) {
for (int k = 0; k < numOfVertices; k++) {
if (matrix[j][k] > (matrix[j][i] + matrix[i][k])
&& (matrix[i][k] != INFTY && matrix[j][i] != INFTY)) {
matrix[j][k] = matrix[j][i] + matrix[i][k];
}
}
}
}

for (int i = 0; i < numOfVertices; i++) {


for (int j = 0; j < numOfVertices; j++) {
(matrix[i][j] == INFTY) ?
cout << "-1" << " " :
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

You might also like