class Floyd_algorithm { public static void main(String[] args) { Floyd_algorithm f = new Floyd_algorithm(4); f.connect(1,0,100);f.connect(2,0,40);f.connect(1,3,20); f.connect(3,2,10); //initial data int c = 0; System.out.println("/t"+" 0" + "/t"+" 1" + "/t"+" 2" + "/t"+" 3" + "/t"); for(int[] a: f.getConnections()) { System.out.print(c+"/t"); c++; for(int i: a) System.out.print((i == INFINITY? "##" : i)+"/t"); System.out.println(); } f.floyd(); System.out.println("/t" + "/t"+"<Result>"); System.out.println("/t"+" 0" + "/t"+" 1" + "/t"+" 2" + "/t"+" 3" + "/t"); c=0; for(int[] a: f.getConnections()) { System.out.print(c+"/t"); for(int i: a) System.out.print((i == INFINITY? "##" : i) + "/t"); System.out.println(); c++; } } private int[][] adjMat; private static final int INFINITY = ~(1<<31); Floyd_algorithm(int size) { adjMat = new int[size][size]; for(int i=0; i<size; i++) for(int j=0; j<size; j++) adjMat[i][j] = INFINITY; } void connect(int from, int to, int length) { adjMat[from][to] = length; } void floyd() { //floyd method for(int y=0; y<adjMat.length; y++) for(int x=0; x<adjMat.length; x++) if(adjMat[y][x] != INFINITY) for(int z=0; z<adjMat.length; z++) if(adjMat[z][y] != INFINITY) { int newLength = adjMat[z][y] + adjMat[y][x]; adjMat[z][x] = newLength < adjMat[z][x] ? newLength : adjMat[z][x]; } } int[][] getConnections() { return adjMat; } }