无向图的广度优先搜索(Java)

一、问题

找到一条1到6的路径

       1  -  2  -  3
       丨    丨    丨
       4  -  5  -  6

 

二、代码

Java

public class UndirectedLinkedGraph {
    private int vertexNum;             // 顶点个数
    private LinkedList<Integer> adj[]; // 邻接表

    public UndirectedLinkedGraph(int vertexNum) {
        this.vertexNum = vertexNum;

        adj = new LinkedList[vertexNum];
        for (int i = 0; i < vertexNum; ++i) {
            adj[i] = new LinkedList<>();
        }
    }

    public void addEdge(int from, int to) { // 无向图一条边存两次
        adj[from].add(to);
        adj[to].add(from);
    }

    /**
     * 创建
     *
     * 1  -  2  -  3
     * 丨    丨    丨
     * 4  -  5  -  6
     */
    public void build() {
        addEdge(1, 2);
        addEdge(1, 4);

        addEdge(2, 3);
        addEdge(2, 5);

        addEdge(3, 6);
        addEdge(4, 5);
        addEdge(5, 6);
    }

    /**
     * 广度优先搜索 (借助队列)
     */
    public void bfs(int start, int target) {
        if (start == target) {
            return;
        }

        //节点是否访问过了
        Boolean[] hasEnqueue = new Boolean[vertexNum];
        for (int i = 1; i < vertexNum; i++) {
            hasEnqueue[i] = false;
        }

        //遍历的辅助队列
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        hasEnqueue[start] = true;

        //遍历的过程(存上一个节点的index)
        Integer[] process = new Integer[vertexNum];
        for(int i=0; i<process.length; i++) {
            process[i] = -1;
        }

        while (!queue.isEmpty()) {
            //队头出队
            Integer head = queue.poll();

            //first能到达的点入队
            for (Integer headCanReceive : adj[head]) {
                if (headCanReceive == target) {
                    process[headCanReceive] = head;
                    printProcess(process, headCanReceive);
                    return;
                }
                if (!hasEnqueue[headCanReceive]) {  //节点出队时,把跟节点连接的所有节点都入队(已经入过队的就不入队了)
                    queue.offer(headCanReceive);
                    hasEnqueue[headCanReceive] = true;
                    process[headCanReceive] = head;
                }
            }
        }
    }

    public void printProcess(Integer[] process, Integer index) {
        if (index >= 0) {
            printProcess(process, process[index]);
            System.out.print(index + "    ");
        }
    }
    
    public static void main(String[] args) {
        UndirectedLinkedGraph graph = new UndirectedLinkedGraph(7);  // 比实际顶点数+1
        graph.build();
        graph.bfs(1, 6);
    }
}

运行结果

1    2    4    6    

 

三、扩展

类似的:

     树的层次遍历 (Java)

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值