Warshall算法:
问题:搭桥找路径:选取一个顶点作为桥梁,考察所有顶点,是否可以通过桥梁到达其它的顶点。
代码实现如下:
package com.jtlyuan;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Warshall {
public void warshallFun(int[][] a){
for(int k=0;k<a.length;k++){/*分别以0->n-1桥梁*/
for(int i=0;i<a.length;i++){/*求取a[j][k]是连通*/
if(a[i][k]==1){
for(int j=0;j<a.length;j++){
if(a[k][j]==1)
a[i][j]=1;
}
}
}
}
}
public void print(int[][] a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
File file = new File("d:"+File.separator+"warshallInput.txt");
try {
System.setOut(new PrintStream(new FileOutputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int[][] a ={{0,1,0,0},{0,0,0,1},{0,0,0,0},{1,0,1,0}};
Warshall ws = new Warshall();
System.out.println("原来的数组:");
ws.print(a);
ws.warshallFun(a);
System.out.println("计算连通性如下:");
ws.print(a);
}
}
运行结果如下:
Floyd算法:
问题:完全最短路径问题:找到从每个顶点到其他所有顶点之间的距离
(
最短路径的长度
)
代码实现如下:
package com.jtlyuan;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Floyd {
public void floydFun(int[][] a){
for(int k=0;k<a.length;k++){/*分别以0->n-1桥梁*/
for(int i=0;i<a.length;i++){/*求取a[i][j]的最短路径*/
for(int j=0;j<a.length;j++){
if(a[i][k]+a[k][j]<a[i][j]){/*取最小值*/
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
}
public void print(int[][] a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
if(a[i][j]==65535){
System.out.print("∞"+" ");
}else{
System.out.print(a[i][j]+" ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
File file = new File("d:"+File.separator+"floydInput.txt");
try {
System.setOut(new PrintStream(new FileOutputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int[][] a ={{0,65535,3,65535},{2,0,65535,65535},{65535,7,0,1},{6,65535,65535,0}};
Floyd floyd = new Floyd();
System.out.println("原来的数组:");
floyd.print(a);
floyd.floydFun(a);
System.out.println("最后的结果:");
floyd.print(a);
}
}
运行结果如下: