0% found this document useful (0 votes)
30 views

Untitled Document 8

The document describes an algorithm that implements Floyd's algorithm to find all-pairs shortest paths in a graph. It takes a graph as input from the user, initializes matrices to store the graph and results, and iterates through the matrices updating paths until it finds the shortest distances between all pairs of vertices.

Uploaded by

api-526462626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Untitled Document 8

The document describes an algorithm that implements Floyd's algorithm to find all-pairs shortest paths in a graph. It takes a graph as input from the user, initializes matrices to store the graph and results, and iterates through the matrices updating paths until it finds the shortest distances between all pairs of vertices.

Uploaded by

api-526462626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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