当前位置:网站首页>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
边栏推荐
- Global and Chinese market of bone adhesives 2022-2028: Research Report on technology, participants, trends, market size and share
- C#聯合halcon脫離halcon環境以及各種報錯解决經曆
- The first game of the 12th Blue Bridge Cup single chip microcomputer provincial competition
- Kotlin基础学习 16
- Oracle 常用SQL
- Uniapp uses canvas to generate posters and save them locally
- Kotlin basic learning 15
- In depth analysis of C language - variable error prone knowledge points # dry goods inventory #
- 焱融看 | 混合云时代下,如何制定多云策略
- 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
猜你喜欢

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
![[untitled] basic operation of raspberry pie (2)](/img/b4/cac22c1691181c1b09fe9d98963dbf.jpg)
[untitled] basic operation of raspberry pie (2)

焱融看 | 混合云时代下,如何制定多云策略

蓝桥杯单片机省赛第十一届
![[HCIA continuous update] overview of dynamic routing protocol](/img/03/83c883afb63b7c63f6879b5513bac3.jpg)
[HCIA continuous update] overview of dynamic routing protocol

Getting started with MQ

蓝桥杯单片机省赛第八届

一文彻底理解评分卡开发中——Y的确定(Vintage分析、滚动率分析等)

Haute performance et faible puissance Cortex - A53 Core Board | i.mx8m mini

傅里叶级数
随机推荐
Large screen visualization from bronze to the advanced king, you only need a "component reuse"!
NLog使用
Kotlin basic learning 16
C#聯合halcon脫離halcon環境以及各種報錯解决經曆
Imageai installation
Gradle foundation | customize the plug-in and upload it to jitpack
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
0 foundation how to learn automated testing? Follow these seven steps step by step and you will succeed
Pointer array & array pointer
数据库文件逻辑结构形式指的是什么
JS generate random numbers
High performance and low power cortex-a53 core board | i.mx8m Mini
It took me only 3 months to jump out of the comfort zone and become an automated test engineer for 5 years
蓝桥杯单片机第四届省赛
潘多拉 IOT 开发板学习(RT-Thread)—— 实验1 LED 闪烁实验(学习笔记)
What is the logical structure of database file
Kotlin基础学习 15
Global and Chinese markets for hand hygiene monitoring systems 2022-2028: Research Report on technology, participants, trends, market size and share
Basic syntax of unity script (8) - collaborative program and destruction method
Basic syntax of unity script (7) - member variables and instantiation