当前位置:网站首页>Lost a few hairs, and finally learned - graph traversal -dfs and BFS
Lost a few hairs, and finally learned - graph traversal -dfs and BFS
2022-07-02 03:39:00 【Road__】
One 、 review
Graph search algorithm is the process of traversing each node in the graph . We classify them according to the order in which their nodes are accessed . Now we will introduce Breadth first traversal (Breadth-first Search abbreviation bfs)、 Depth-first traversal (Depth-first Search abbreviation dfs) . These two algorithms are the basis of graph traversal , It is also commonly used in the preliminary exploration of data and many subsequent graph routing algorithms (Pathfinding Algorithm) Are based on this foundation .
Two 、 Breadth first traversal
3.1 brief introduction
Ergodic graph algorithm BFS Is the most commonly used method .
BFS Is a traversal algorithm , Select a node ( Source or starting node ) Start traversing and traverse the graph layer by layer , To explore neighbor nodes ( Nodes directly connected to the source node ). then , You must move to the next neighbor node .
just as BFS As your name implies , You need to traverse the graph as follows :
- First move horizontally , Access all nodes of the current layer
- Move to the next level
The following picture shows the sequence of traversal :

BFS Of Time complexity by O(V + E), among V It's the number of nodes ,E It's the number of sides .
3.2 Code
public void compute(int startId) {
System.out.println("=========== BFS ===========");
boolean[] visited = new boolean[graphApi.getVertexSize()];
//visited[startId] = true;
List<Integer> currentIds = new ArrayList<>();
currentIds.add(startId);
int depth = 1;
while (currentIds.size() != 0) {
Set<Integer> nextId = new HashSet<Integer>();
System.out.println("depth is " + (depth++) + " neighbors is " + currentIds);
for (Integer id : currentIds) {
if(visited[id]) {
continue;
}
visited[id] = true;
int[] edge = graphApi.getEdge(id);
if (edge != null) {
for (int eId : edge) {
nextId.add(eId);
}
}
}
currentIds.clear();
currentIds.addAll(nextId);
}
System.out.println("");
}
3、 ... and 、 Depth-first traversal
3.1. brief introduction
DFS The algorithm is a recursive algorithm that uses the idea of backtracking . If possible , It involves a detailed search of all nodes , If possible , By backtracking .
ad locum , word backtrack It means that when you move forward and there are no more nodes along the current path , You move backward on the same path to find the node to traverse . All nodes will be accessed on the current path , Until all unreached nodes are traversed , Then choose the next path .
DFS This recursive feature of can be implemented using stack . The basic idea is as follows :
Select a starting node and push all its adjacent nodes onto the stack .
Pop a node from the stack to select the next node to access and push all its adjacent nodes onto the stack . Repeat the process , Until the stack is empty . however , Make sure that the accessed node is marked . This will prevent you from accessing the same node multiple times . If you do not mark the visited node and you visit the same node multiple times , You may fall into an infinite loop .
The following picture shows the sequence of traversal :
DFS Of Time complexity by O(V + E), among V It's the number of nodes ,E It's the number of sides .
3.2. Code implementation
1. Recursive implementation
public void dfs(int i, boolean[] visited, GraphApi graphApi) {
System.out.print(i);
visited[i] = true;
int[] edgeIds = graphApi.getEdge(i);
if (edgeIds == null) {
System.out.print(" -> ");
return;
} else {
System.out.print(" -> ");
}
for (int edgeId : edgeIds) {
if(!visited[edgeId]) {
dfs(edgeId, visited, graphApi);
}
}
}
2. Simulate stack implementation
public void compute(int i, boolean[] visited) {
Stack<Integer> stack = new Stack<>();
// Root node stack
stack.push(i);
visited[i] = true;
while (!stack.isEmpty()) {
Integer id = stack.pop();
System.out.print(id + " -> ");
// Logical processing
int[] edge = graphApi.getEdge(id);
if(edge != null) {
for (int item : edge) {
if(!visited[item]) {
stack.push(item);
visited[item] = true;
}
}
}
}
}
Detailed source code address :
https://github.com/RoadTLife/TGraph
边栏推荐
- Imageai installation
- What is the binding path of SAP ui5
- 蓝桥杯单片机省赛第九届
- This article describes the step-by-step process of starting the NFT platform project
- 跳出舒适区,5年点工转型自动化测试工程师,我只用了3个月时间
- Kotlin基础学习 14
- "Analysis of 43 cases of MATLAB neural network": Chapter 42 parallel operation and neural network - parallel neural network operation based on cpu/gpu
- Introduction to Robotics II. Forward kinematics, MDH method
- [database]jdbc
- C # joint Halcon's experience of breaking away from Halcon environment and various error reporting solutions
猜你喜欢

MySQL advanced (Advanced) SQL statement (II)

How to establish its own NFT market platform in 2022

Eight steps of agile development process

Large screen visualization from bronze to the advanced king, you only need a "component reuse"!
![[yolo3d]: real time detection of end-to-end 3D point cloud input](/img/5e/f17960d302f663db75ad82ae0fd70f.jpg)
[yolo3d]: real time detection of end-to-end 3D point cloud input

Get started with Aurora 8b/10b IP core in one day (5) -- learn from the official routine of framing interface

Account management of MySQL

Gradle foundation | customize the plug-in and upload it to jitpack

Getting started with MQ

蓝桥杯单片机省赛第十一届第二场
随机推荐
Kotlin basic learning 13
MD5 of Oracle
High performance and low power cortex-a53 core board | i.mx8m Mini
Uniapp uses canvas to generate posters and save them locally
What do you know about stock selling skills and principles
Kotlin基础学习 14
微信小程序中 在xwml 中使用外部引入的 js进行判断计算
It took me only 3 months to jump out of the comfort zone and become an automated test engineer for 5 years
汇率的查询接口
What is the binding path of SAP ui5
Object oriented thinking
Global and Chinese market of bone adhesives 2022-2028: Research Report on technology, participants, trends, market size and share
一天上手Aurora 8B/10B IP核(5)----从Framing接口的官方例程学起
Go execute shell command
PY3 link MySQL
0基础如何学习自动化测试?按照这7步一步一步来学习就成功了
Xlwings drawing
傅里叶级数
《MATLAB 神经网络43个案例分析》:第42章 并行运算与神经网络——基于CPU/GPU的并行神经网络运算
Analyse de 43 cas de réseaux neuronaux MATLAB: Chapitre 42 opérations parallèles et réseaux neuronaux - - opérations parallèles de réseaux neuronaux basées sur CPU / GPU