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

/*

* INSTRUCTION:
* This is a Java starting code for hw6_2.
* When you finish the development, download this file.
* Note that the current filename is "Main.java".
* But rename it to "Main_hw6_2.java".
* After that, upload the renamed file on Canvas.
*/

// Finish the head comment with Abstract, Name, and Date.


/*
* Title: Main_hw6_2.java
* Abstract: This program implements the Floyd algorithm to display all-pairs
shortest paths as covered in class
* Name: Anthony Matricia
* Date: 02/19/2024
*/

import java.util.Scanner;

public class Main {


final static int INF = 99999; // makeshift inf value

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in); // create scanner
int V = scanner.nextInt(); // get # of vertices
int[][] graph = new int[V][V]; // create graph

// read input graph


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
int value = scanner.nextInt();
graph[i][j] = (value == -1) ? INF : value;
}
}

// floyd-warshall algorithm sourced from -


// (https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/)
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (graph[i][k] + graph[k][j] < graph[i][j]) {
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}

// replace inf back to -1 for out


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (graph[i][j] == INF) {
graph[i][j] = -1;
}
}
}

// out shortest distance matrix


printMatrix(graph);
}

// util func to print matrix


public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] == INF)
System.out.print("INF");
else
System.out.print(matrix[i][j]);
if (j < matrix.length - 1)
System.out.print(" ");
}
System.out.println();
}
}
}

You might also like