0

我写了一个 bfs 算法,但我知道我必须找出两点之间的最短距离。我可以在我的代码中以某种方式实现它吗?

public static void bfsearch(Graph<Vertex, Edge<Vertex>> G, Vertex S){

        State[] color = new State [G.getNumberVertices()];
        int[] dist = new int [G.getNumberVertices()];
        Vertex[] pred = new Vertex [G.getNumberVertices()];
        Vertex temp;

        for(int i=0; i<color.length; i++){
            color[i] = State.WHITE;
            dist[i] = Integer.MAX_VALUE;
            pred[i] = null;
        }
        color[S.getId()] = State.GREY; dist[S.getId()] = 0; pred[S.getId()] = null;     
        Queue<Vertex> Q = new LinkedList<Vertex>();
        Q.add(S);
        while(!Q.isEmpty()){
            temp = Q.remove();
            for(Vertex x:G.getNeighbours(temp)){
                if(color[x.getId()] == State.WHITE ){
                    color[x.getId()] = State.GREY;
                    dist[x.getId()] = dist[temp.getId()] + 1;
                    pred[x.getId()] = temp;
                    Q.add(x);
                }
            }
            color[temp.getId()] = State.BLACK;
            System.out.println("(Node "+temp+", "+"Pred="+pred[temp.getId()]+" Distance="+dist[temp.getId()]+")");
        }
    }
4

0 回答 0