日期:2020-10-25
作者:19届 LZ
标签:JAVA 离散数学
实现较简单,具体过程就不阐述了,哈哈
import java.util.*;
public class Pathprogram {
int vertices;//结点数
int path[][][];//路径
int t;
int [][] getpath(){//返回路径
return path[t];
}
Pathprogram(int vertices){//初始化路径
this.vertices=vertices;
path=new int[vertices][vertices][vertices];
for(int i=0;i<vertices;i++){//初始化
Arrays.fill(path[0][i],0x3f3f3f);
path[0][i][i]=0;
}
Scanner in=new Scanner(System.in);
int x;
int y;
int w;
while((x=in.nextInt())!=-1&&(y=in.nextInt())!=-1&&(w=in.nextInt())!=-1){
path[0][x][y]=w;
path[0][y][x]=w;
}
in.close();
}
void Hedetniemi(){
t=0;
boolean flag=false;//false表示前后两个矩阵不相等
while(t!=vertices-1&&flag==false){ //一个图的生成树,最多有vertices-1个边
t++; //或者已经前后两个矩阵相等,遍历结束
for(int i=0;i<vertices;i++){
for(int j=0;j<vertices;j++){
path[t][i][j]=path[t-1][i][j];
for(int k=0;k<vertices;k++){
//判断是否有路径比已储存路径更短
path[t][i][j]=Math.min(path[t][i][j],path[t-1][i][k]+path[0][k][j]);
}
}
}
flag=true;//假设前后两个矩阵相等
for(int i=0;i<vertices;i++){
if(!Arrays.equals(path[t][i],path[t-1][i])){//检查前后两个矩阵是否相等
flag=false;
}
}
}
}
StringBuffer findpath(int x,int y){
int waylength=path[t][x][y];
StringBuffer shortestpath=new StringBuffer();//记录经过的结点
//不存在路径
if(path[t][x][y]==0x3f3f3f){
shortestpath.append(-1);
return shortestpath;
}
//存在路径
shortestpath.append(y+">-");//记录终点
int p=t;//记录
while(path[p][x][y]==path[p-1][x][y]){//找到x达到y的第一个时刻
p--;
}
while(p>0){
for(int i=0;i<vertices;i++){
if(path[p-1][x][i]+path[0][i][y]==waylength){//反向求x到y的路径
waylength-=path[0][i][y];
shortestpath.append(i+">-");
y=i;
}
}
p--;
}
shortestpath.append(x);//加上起始节点
shortestpath.reverse();
return shortestpath;
}