当前位置: 首页 > news >正文

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

文章目录

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

1. 代码仓库

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

2. 广度优先遍历图解

在这里插入图片描述

3.主要代码

  1. 原点入队列
  2. 原点出队列的同时,将与其相邻的顶点全部入队列
  3. 下一个顶点出队列
  4. 出队列的同时,将与其相邻的顶点全部入队列
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. 完整代码

输入文件

7 9
0 1
0 3
1 2
1 6
2 3
2 5
3 4
4 5
5 6
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());}
}

在这里插入图片描述

http://www.lryc.cn/news/204321.html

相关文章:

  • vue3 v-model的使用
  • Ubuntu 20.04 安装 Docker
  • vue el-dialog弹出框自定义指令实现拖拽改变位置-宽度-高度
  • 玄铁C906——物理内存保护(PMP)介绍
  • 【进阶C语言】编译与链接、预处理符号详解
  • spring.profiles生效顺序
  • 【经典PageRank 】02/2 算法和线性代数
  • 【微客云】91优惠话费充值API接口开发功能介绍
  • Kubernetes - 一键安装部署 K8S(附:Kubernetes Dashboard)
  • Camera2开发基础知识篇——手机影像参数
  • Unity之ShaderGraph如何实现无贴图水球效果
  • 【C语言】指针错题(类型分析)
  • prosemirror 学习记录(二)创建 apple 节点
  • 自然语言处理---迁移学习
  • node 第十天 原生node封装一个简易的服务器
  • php实战案例记录(25)intval函数的用法
  • laravel框架介绍(二) composer命令下载laravel报错
  • 代码签名证书到期了怎么续费?
  • JAVA 同城服务预约家政小程序开发的优势和运营
  • 基于粒子群算法的无人机航迹规划-附代码
  • 前端使用qrcodejs2插件实现根据网址生成二维码
  • A股风格因子看板 (2023.10 第11期)
  • anaconda安装python 3.11
  • 问题:EventSource 收不到流数据及 EventSource 的 onmessage 方法为null
  • P2 B+树索引
  • 爬虫知识之BeautifulSoup库安装及简单介绍
  • 如何有效取代FTP来帮助企业快速传输大文件
  • 免登陆积分商城原理
  • muduo源码学习base——Atomic(原子操作与原子整数)
  • 最短路相关笔记