图论04-【无权无向】-图的广度优先遍历

文章目录

  • [1. 代码仓库](#1. 代码仓库)
  • [2. 广度优先遍历图解](#2. 广度优先遍历图解)
  • 3.主要代码
  • [4. 完整代码](#4. 完整代码)

1. 代码仓库

https://github.com/Chufeng-Jiang/Graph-Theory

2. 广度优先遍历图解

3.主要代码

  1. 原点入队列
  2. 原点出队列的同时,将与其相邻的顶点全部入队列
  3. 下一个顶点出队列
  4. 出队列的同时,将与其相邻的顶点全部入队列
cpp 复制代码
private void bfs(int s){ //使用循环
    Queue<Integer> queue = new LinkedList<>();
    queue.add(s);
    visited[s] = true;
    while(!queue.isEmpty()){ //只要不是空就不停地出队
        int v = queue.remove(); // v记录队首元素 | 相邻顶点入队后,重新进入while循环,队首出队
        order.add(v); //添加到order数组中,order数组装的是按照BFS顺序遍历的顶点

        for(int w: G.adj(v))
            if(!visited[w]){
                queue.add(w); // 相邻的顶点入队列
                visited[w] = true;
            }
    }
}

复杂度:O(V+E)

4. 完整代码

输入文件

bash 复制代码
7 9
0 1
0 3
1 2
1 6
2 3
2 5
3 4
4 5
5 6
cpp 复制代码
package Chapt04_BFS_Path._0401_Graph_BFS_Queue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class GraphBFS {

    private Graph G;
    private boolean[] visited;

    private ArrayList<Integer> order = new ArrayList<>(); // 存储遍历顺序

    public GraphBFS(Graph G){
        this.G = G;
        visited = new boolean[G.V()];

        //遍历所有连通分量
        for(int v = 0; v < G.V(); v ++)
            if(!visited[v])
                bfs(v);
    }

    private void bfs(int s){ //使用循环
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        while(!queue.isEmpty()){ //只要不是空就不停地出队
            int v = queue.remove(); // v记录队首元素 | 相邻顶点入队后,重新进入while循环,队首出队
            order.add(v); //添加到order数组中,order数组装的是按照BFS顺序遍历的顶点

            for(int w: G.adj(v))
                if(!visited[w]){
                    queue.add(w); // 相邻的顶点入队列
                    visited[w] = true;
                }
        }
    }

    //取出遍历顺序
    public Iterable<Integer> order(){
        return order;
    }

    public static void main(String[] args){

        Graph g = new Graph("g1.txt");
        GraphBFS graphBFS = new GraphBFS(g);
        System.out.println("BFS Order : " + graphBFS.order());
    }
}
相关推荐
焦耳加热21 小时前
阿德莱德大学Nat. Commun.:盐模板策略实现废弃塑料到单原子催化剂的高值转化,推动环境与能源催化应用
人工智能·算法·机器学习·能源·材料工程
wan5555cn1 天前
多张图片生成视频模型技术深度解析
人工智能·笔记·深度学习·算法·音视频
u6061 天前
常用排序算法核心知识点梳理
算法·排序
蒋星熠1 天前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
小欣加油1 天前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream1 天前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
王璐WL1 天前
【c++】c++第一课:命名空间
数据结构·c++·算法
空白到白1 天前
机器学习-聚类
人工智能·算法·机器学习·聚类
索迪迈科技1 天前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
zzzsde1 天前
【数据结构】队列
数据结构·算法