广度优先遍历

//对一个结点进行广度优先遍历
    public void bfs(boolean[] isVisited, int i){
        int u;  //队头结点的suoyin
        int w;  //邻接结点w
        //创建队列
        LinkedList queue = new LinkedList<>();
        //访问结点
        System.out.print(getValueByIndex(i)+"=>");
        //标记为已访问
        isVisited[i] = true;
        //将结点接入队列
        queue.addLast(i);
        //如果队头元素不为null,就继续遍历
        while ( !queue.isEmpty()){
            //取出队头的结点下标
            u = (Integer) queue.removeFirst();
            //得到u的下一个结点w
            w = getFirstNeighbor(u);
            while ( w != -1){
                //判断是否访问过
                if (!isVisited[w]){
                    //没被访问过就访问
                    System.out.print(getValueByIndex(w)+"=>");

                    //标记为已访问
                    isVisited[w] = true;
                    //入队列
                    queue.addLast(w);
                }
                w= getNextNeighbor(u,w);
            }

        }
    }
    //对bfs重载
    public void bfs(){
        isVisited = new boolean[5];
        //遍历所有的结点,进行dfs回溯
        for (int i = 0; i < getNumOfVertex(); i++) {
            if (!isVisited[i]){
                bfs(isVisited,i);
            }
        }
    }


Last updated