目录
图的遍历,即将图内所有顶点都访问一遍。
有两种遍历方式:
以下图的遍历为例:

DFS(depth first search),深度优先搜索,先跑到叶节点,沿着原路返回,沿途遍历其他节点。
代码示例:
- public class DFS {
- //图
- static int[][] graph=new int[7][7];
- //访问记录
- static boolean[] isVisited=new boolean[7];
- static {
- graph[0][1]=1;graph[0][2]=1;graph[0][3]=1;
- graph[1][0]=1;graph[1][2]=1;
- graph[2][0]=1;graph[2][1]=1;graph[2][3]=1;graph[2][4]=1;graph[2][5]=1;
- graph[3][0]=1;graph[3][2]=1;graph[3][4]=1;
- graph[4][2]=1;graph[4][3]=1;
- graph[5][2]=1;
- graph[5][6]=1;
- graph[6][5]=1;
- }
-
- public static void DFS(int i){
- System.out.println(i);
- isVisited[i]=true;
- for(int j=0;j
- if(graph[i][j]==1&&isVisited[j]==false){
- DFS(j);
- }
- }
- }
-
- public static void main(String[] args) {
- DFS(0);
- }
- }
11.3.BFS
BFS(Breadth first search),广度优先搜索,先遍历一度关系(直接相连),再遍历二度关系(直接相连的直接相连),再遍历三度关系(直接相连的直接相连的直接相连)……直到遍历完整个图。过程类似于树的层序遍历。
- public class BFS {
- //图
- static int[][] graph=new int[7][7];
- //访问记录
- static boolean[] isVisited=new boolean[7];
- //队列
- static LinkedList
queue=new LinkedList(); - static {
- graph[0][1]=1;graph[0][2]=1;graph[0][3]=1;
- graph[1][0]=1;graph[1][2]=1;
- graph[2][0]=1;graph[2][1]=1;graph[2][3]=1;graph[2][4]=1;graph[2][5]=1;
- graph[3][0]=1;graph[3][2]=1;graph[3][4]=1;
- graph[4][2]=1;graph[4][3]=1;
- graph[5][2]=1;
- graph[5][6]=1;
- graph[6][5]=1;
- }
-
- public static void BFS(){
- while(!queue.isEmpty()){
- int i=queue.poll();
- System.out.println("出队:"+i);
- isVisited[i]=true;
- for(int j=0;j
- if(graph[i][j]==1&&isVisited[j]==false) {
- System.out.println("入队:"+j);
- isVisited[j]=true;
- queue.offer(j);
- }
- }
- }
- }
-
- public static void main(String[] args) {
- queue.offer(0);
- BFS();
- }
- }
-
相关阅读:
Scss
hiredis在vs2010上编译不通过及解决方法
【Linux常用(实用)命令大全】
‘mysql‘不是内部或外部命令,也不是可运行的程序或批处理文件
【C++ 学习 ㉕】- 万字详解 unordered_map 和 unordered_set(哈希表的查找和容器的模拟实现)
T1080 余数相同问题(信息学一本通C++)
【MATLAB教程案例42】语音信号的MFCC特征提取matlab仿真
探索神经网络架构教程视频,设计神经网络的步骤
javascript动态创建script元素后,动态加载外部js文件
【语言模型生成分子更好】Language models can learn complex molecular distributions
-
原文地址:https://blog.csdn.net/Joker_ZJN/article/details/128176476