时间复杂度:O(n^3)
import java.util.Scanner;
public class Main {
public static int[][] readG(Scanner in,int n)
{
int[][] G=new int[n][n];
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
G[i][j]=in.nextInt();
if(G[i][j]==-1)
G[i][j]=Integer.MAX_VALUE;
}
}
return G;
}
public static void print(int[][] x)
{
for(int i=0;i<x.length;i++)
{
for(int j=0;j<x.length;++j)
{
System.out.print(x[i][j]+" ");
}
System.out.println();
}
}
public static void printP(boolean[][][] p,int n)
{
System.out.print(" ");
for(int j=0;j<n;j++)
{
System.out.print(j+" ");
}
System.out.println();
for(int i=0;i<n;i++)
{
//System.out.print(i+" ");
for(int j=0;j<n;j++)
{
System.out.print(i+":"+j+" ");
for(int k=0;k<n;k++)
{
System.out.print(p[i][j][k]+" ");
}
System.out.println();
}
}
}
public static void shortestpath_floyd(int[][] G, boolean[][][] P,int[][] D)
{
int v,w,u;
for(v=0;v<G.length;++v) //各对节点之间初始已知路径及距离
{
for(w=0;w<G.length;++w)
{
D[v][w]=G[v][w];
//System.out.print("start ");
for(u=0;u<G.length; ++u)
{
//System.out.print(v+":"+w+":"+u+" "+P[v][w][u]+" ");
P[v][w][u]=false;
//System.out.println(P;
}
//System.out.println();
if(D[v][w]<Integer.MAX_VALUE) //从v到w有直接路径
{
P[v][w][v]=true; P[v][w][w]=true;
}
// System.out.print("end ");
// for(u=0;u<G.length; ++u)
// {
// System.out.print(v+":"+w+":"+u+" "+P[v][w][u]+" ");
// P[v][w][u]=false;
// //System.out.println(P;
// }
// System.out.println();
}
}
printP(P,3);
print(D);
for(u=0;u<G.length;++u)
{
System.out.println(u);
for(v=0;v<G.length;++v)
{
System.out.print("old ");
for(w=0;w<G.length;++w)
{
System.out.print(D[v][w]+" ");
}
System.out.println();
for(w=0;w<G.length;++w)
{
if(D[v][u]+D[u][w]<D[v][w]&&D[v][u]<Integer.MAX_VALUE&&D[u][w]<Integer.MAX_VALUE) //从v经u到w的一条路径更短
{
D[v][w]=D[v][u]+D[u][w];
for(int i=0;i<G.length;++i)
P[v][w][i]=P[v][u][i]||P[u][w][i];
}
}
System.out.print("new ");
for(w=0;w<G.length;++w)
{
System.out.print(D[v][w]+" ");
}
System.out.println();
System.out.println();
}
}
System.out.println();
printP(P,3);
print(D);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
//System.out.println(Integer.MAX_VALUE+Integer.MAX_VALUE<Integer.MAX_VALUE);
int[][] G=readG(in,3);
print(G);
boolean[][][] P=new boolean[3][3][3];
int[][] D=new int[3][3];
shortestpath_floyd(G, P, D);
}
}
/*
测试数据
0 4 11
6 0 2
3 -1 0
*/