用通俗的语言来描述的话,首先我们的目标是寻找从点i到点j的最短路径。从动态规划的角度看问题,我们需要为这个目标重新做一个诠释(这个诠释正是动态规划最富创造力的精华所在)。
public void floyd() {
int[][] dist=new int[vertex.length][vertex.length];
int[][] prev=new int[vertex.length][vertex.length];
for(int i=0;i<vertex.length;i++) {
for(int j=0;j<vertex.length;j++) {
dist[i][j]=getWeight(i, j);
prev[i][j]=j;
}
}
for(int k=0;k<vertex.length;k++) {
for(int i=0;i<vertex.length;i++) {
for(int j=0;j<vertex.length;j++) {
int tmp = (dist[i][k]==INF || dist[k][j]==INF) ? INF : (dist[i][k] + dist[k][j]);
if (dist[i][j] > tmp) {
dist[i][j] = tmp;
prev[i][j] = prev[i][k];
}
}
}
}
System.out.printf("floyd: \n");
for (int i = 0; i < vertex.length; i++) {
for (int j = 0; j < vertex.length; j++)
System.out.printf("%2d ", dist[i][j]);
System.out.printf("\n");
}
}
   
|