Floyed 算法:
import java.util.Arrays;
public class Floyed {
public static int[][] floyed(int[][] graph){
int[][] path=new int[graph.length][graph[0].length];
for(int i=0;i<path.length;i++){
for(int j=0;j<path[0].length;j++){
if(graph[i][j]==Integer.MAX_VALUE) path[i][j]=-1;
//else path[i][j]=j;//从前往后找
else path[i][j]=i;//从后往前找
}
}
for(int k=0;k<graph.length;k++){
for(int i=0;i<graph.length;i++){
for(int j=0;j<graph.length;j++){
if(graph[i][k]==Integer.MAX_VALUE||graph[k][j]==Integer.MAX_VALUE){
continue;
}
if(graph[i][k]+graph[k][j]<graph[i][j]){
graph[i][j]=graph[i][k]+graph[k][j];
//path[i][j]=k;//这种写法是不对的,因为这只能说明从i到j经过k,k不一定是i的直接后继 如路径[0,3,4,2,5] 则k可能是4,这只与比较顺序有关系
path[i][j]=path[k][j]; //path[i][j]=path[k][j];是记录前驱位置,与else path[i][j]=i;对应
}
}
}
}
return path;
}
public static int[][] floyed2(int[][] graph){
int[][] path=new int[graph.length][graph[0].length];
for(int i=0;i<path.length;i++){
for(int j=0;j<path[0].length;j++){
if(graph[i][j]==Integer.MAX_VALUE) path[i][j]=-1;
else path[i][j]=j;//从前往后找
//else path[i][j]=i;//从后往前找
}
}
for(int k=0;k<graph.length;k++){
for(int i=0;i<graph.length;i++){
for(int j=0;j<graph.length;j++){
if(graph[i][k]==Integer.MAX_VALUE||graph[k][j]==Integer.MAX_VALUE){
continue;
}
if(graph[i][k]+graph[k][j]<graph[i][j]){
graph[i][j]=graph[i][k]+graph[k][j];
path[i][j]=path[i][k];//这种记录路径的方法很重要 path[i][j]=k 是记录后继位置 ,与else path[i][j]=j;对应
//path[i][j]=path[k][j]; //path[i][j]=path[k][j];是记录前驱位置,与else path[i][j]=i;对应
}
}
}
}
return path;
}
static final int max=Integer.MAX_VALUE;
public static void main(String[] args) {
int[][] graph={
{0,2,6,4},
{max,0,3,max},
{7,max,0,1},
{5,max,12,0}
};
int[][] path=floyed2(graph);
for(int i=0;i<graph.length;i++){
System.out.println(Arrays.toString(graph[i]));
}
for(int i=0;i<path.length;i++){
System.out.println(Arrays.toString(path[i]));
}
}
}