Floyd

You might also like

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

/*

* Title: Main_hw6_2.java
* Abstract: This program implements the Floyd algorithm to display all-pairs
shortest paths as covered in class.
* Name: Alex O'Brien
* Date: 2/21/23
*/

import java.util.Scanner;

class Main
{
// global variables
static Scanner kb = new Scanner(System.in);

// functions
// gathering input from user, building matrix
static int[][] buildMatrix() {
int vertices = kb.nextInt();
int[][] matrix = new int[vertices][vertices];
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
matrix[i][j] = kb.nextInt();
}
}
return matrix;
}

// floyds algorithm
static void floyds(int[][] matrix) {
for (int k = 0; k < matrix.length; k++) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
// skip current iteration if no path exists
if (matrix[i][k] == -1 || matrix[k][j] == -1)
continue;
// if not infinity, check to see if path is shorter
else if (matrix[i][j] != -1) {
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
// make equal to path
matrix[i][j] = matrix[i][k] + matrix[k][j];
// if infinity, make equal to path
} else if (matrix[i][j] == -1)
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
}

// display matrix
static void display(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
// at end of line, don't print space
if (j != matrix.length - 1)
System.out.printf("%d ", matrix[i][j]);
else
System.out.print(matrix[i][j]);
}
System.out.print("\n");
}
}

// driver program
public static void main(String[] args) {
int[][] matrix = buildMatrix();
floyds(matrix);
display(matrix);
kb.close();
}
}

You might also like