BFS实现最小路径

package com.Test.Graph;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class MinPathBFS {

    private NewGraph graph;
    private NewGraph.Vertex startVertex;
    private NewGraph.Vertex endVertex;
    private String  endPoint;

    public static void main(String[] args){
        MinPathBFS minPathBFS=new MinPathBFS();
        minPathBFS.findMinPath();
        minPathBFS.printMinPath();
    }

    public MinPathBFS(){
        graph=new NewGraph();
    }

    public void findMinPath(){
        intitalPath();
        Queue<NewGraph.Vertex> queue=new LinkedList<>();

        NewGraph.Vertex nowVertex;
        NewGraph.Vertex firstVertex;
        queue.offer(startVertex);
        while(!queue.isEmpty()){
            nowVertex=queue.poll();
            firstVertex=nowVertex;
            nowVertex.isVisited=true;
            if (nowVertex.name.equals(endPoint)) {      //检测取出vertex是否为最后一个vertex
                System.out.println("We find it!!!!! ");
                break;
            }


            while(nowVertex.nextVertex!=null){      //将取出的vertex的所有后续节点都放进queue中去
                nowVertex=nowVertex.nextVertex;
                if (!graph.vertexList[nowVertex.index].isVisited){
                    queue.offer(graph.vertexList[nowVertex.index]);
                    graph.vertexList[nowVertex.index].preVertex=firstVertex;        //Vertex放进queue时将其preVertex设置为fvertex
                }
            }
        }
    }

    public void printMinPath(){
        Stack<NewGraph.Vertex> stack=new Stack<>();
        stack.push(endVertex);
        System.out.println(endVertex.preVertex!=null);
        while(endVertex.preVertex!=null){
            endVertex=endVertex.preVertex;
            stack.push(endVertex);
        }
        System.out.print(stack.pop().name);
        while(!stack.isEmpty()){
            System.out.print(" -> "+stack.pop().name);
        }
        System.out.println();
    }

    public void intitalPath(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("Please entet start point and end point: ");
        String startPoint=scanner.next();
        endPoint=scanner.next();
        startVertex=graph.getVertex(startPoint);
        endVertex=graph.getVertex(endPoint);
        if (!graph.hasVertex(startPoint))
            System.out.println("this graph don't has the start point");
        else if(!graph.hasVertex(endPoint))
            System.out.println("this graph don't has the end point");
        else
            System.out.println("success");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值