Skip to content

Instantly share code, notes, and snippets.

@bvolpato
Last active August 27, 2020 18:18
Show Gist options
  • Save bvolpato/b442fc0a333a2c1144e36872af1ed018 to your computer and use it in GitHub Desktop.
Save bvolpato/b442fc0a333a2c1144e36872af1ed018 to your computer and use it in GitHub Desktop.
Algorithm - Floyd-Warshall
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Floyd-Warshall Java Implementation
*/
public class FloydWarshall {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// n x n
int n = sc.nextInt();
// source
int s = sc.nextInt();
// target
int t = sc.nextInt();
int[][] D = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
D[i][j] = sc.nextInt();
}
}
// Floyd-Warshall Algorithm
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (D[i][j] > D[i][k] + D[k][j]) {
D[i][j] = D[i][k] + D[k][j];
}
}
}
}
System.out.println(D[s][t]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment