Hedetniemi’s Algorithm实现

日期: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;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

中南大学苹果实验室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值