当前位置:网站首页>Depth first traversal (DFS) and breadth first traversal (BFS)
Depth first traversal (DFS) and breadth first traversal (BFS)
2022-07-06 21:44:00 【HairLossException】
List of articles
Depth-first traversal
Depth first traversal starts from the initial vertex , The initial vertex may have an adjacent vertex , The strategy of depth first traversal is to visit the first adjacent vertex first , Then use the accessed adjacent vertex as the initial vertex to access its first adjacent vertex .
Depth first traversal steps
(1) Visit vertex v, And access points v Mark as accessed .
(2) Successively v Of the adjacent points that are not accessed , Depth first traversal of the graph ; Until the graph neutralizes v Vertices that have paths are all accessed .
(3) If there are still vertices in the graph that are not accessed , From a vertex that has not been visited , Do depth first traversal again , Until all the vertices in the graph have been visited .
↑↑↑( Above this wx official account )
Visual demonstration of data structure and Algorithm
Code
public class Graph {
/* Store a collection of vertices */
private ArrayList<String> vertexList;
/* Store the adjacency matrix corresponding to the graph */
private int[][] edges;
/* The number of edges */
private int numOfEdges;
/* Record whether a vertex has been accessed */
private boolean[] isVisited;
public static void main(String[] args) {
String[] vertexs = {
"A","B","C","D","E"};
/* Create a graph object */
Graph graph = new Graph(vertexs.length);
/* Add vertex */
for (String vertex:vertexs) {
graph.insertVertex(vertex);
}
/* Add edge */
graph.insertEdges(0,1,1);
graph.insertEdges(0,2,1);
graph.insertEdges(1,2,1);
graph.insertEdges(1,3,1);
graph.insertEdges(1,4,1);
System.out.println(" Depth-first traversal ");
graph.dfs();
}
public Graph(int n){
/* Initialize matrix and set */
edges = new int[n][n];
vertexList = new ArrayList<>(n);
isVisited = new boolean[n];
numOfEdges = 0;
}
/** * Get the subscript of the first adjacent vertex * @param index * @return If it exists, return the corresponding subscript; otherwise, return -1 */
public int getFirstNeighbor(int index){
for (int i = 0; i < vertexList.size(); i++) {
if (edges[index][i] > 0){
return i;
}
}
return -1;
}
/** * Get the adjacent vertex subscript that has not been accessed * @param v1 The current peak * @param v2 Vertices that have been visited * @return The subscript of the next adjacent vertex */
public int getNextNeighbor(int v1,int v2){
for (int j = v2+1; j < vertexList.size(); j++) {
if (edges[v1][j] > 0){
return j;
}
}
return -1;
}
/** * Depth-first traversal * @param isVisited Record whether the vertex has been visited * @param i Current vertex */
public void dfs(boolean[] isVisited,int i){
System.out.print(getValueByIndex(i)+"->");
isVisited[i] = true;
int neighbor = getFirstNeighbor(i);
while(neighbor != -1){
// Indicates that there are adjacent vertices
if (!isVisited[neighbor]){
/*neighbor Not interviewed */
dfs(isVisited,neighbor);
}
/*neighbor The vertex has been accessed */
neighbor = getNextNeighbor(i,neighbor);
}
}
/* heavy load dfs*/
public void dfs(){
/* Traverse all the vertices */
for (int i = 0; i < getNumOfVertex(); i++) {
if (!isVisited[i]){
dfs(isVisited,i);
}
}
}
/* Insert vertex */
public void insertVertex(String vertex){
vertexList.add(vertex);
}
/** * Insert edge * @param v1 Subscript of vertex in adjacency matrix * @param v2 Subscript of vertex in adjacency matrix * @param weight A weight */
public void insertEdges(int v1,int v2,int weight){
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
/* Get the number of vertices */
public int getNumOfVertex(){
return vertexList.size();
}
/* According to the subscript index Get the corresponding data */
public String getValueByIndex(int index){
return vertexList.get(index);
}
}
Running results
Depth-first traversal
A->B->C->D->E
Process finished with exit cod
Breadth first traversal
The breadth first traversal of a graph is similar to the sequence traversal of a tree , Breadth first traversal requires a queue to maintain the order of visited vertices , In order to access the adjacent vertices of these vertices in this order .
Breadth first traversal steps
(1) Access the initial vertex v And mark the vertices v Has been interviewed .
(2) Put the vertex v The team .
(3) When the queue is not empty, take out the head node of the queue u, If the queue is empty, the algorithm ends .
(4) Find the header node u The unreachable adjacent vertex of .
(5) Queue the adjacent vertices that are not accessed and mark them as accessed .
(6) Jump to step 3 Until all the vertices in the graph have been visited .
Code
/** * Breadth first traversal * @param isVisited Whether the vertex has been accessed * @param i Current vertex */
public void bfs(boolean[] isVisited,int i){
int u; // The queue header node corresponds to the subscript
int neighbor; // Adjacency vertex
/* queue , Record the order of accessing the top and bottom */
LinkedList queue = new LinkedList();
System.out.print(getValueByIndex(i)+"->");
isVisited[i] = true;
queue.addLast(i);
while(!queue.isEmpty()){
/* Take out the coordinates of the queue head node */
u =(Integer) queue.removeFirst();
neighbor = getFirstNeighbor(u);
while(neighbor != -1){
// Have adjacent vertices
/* Judge whether you have visited */
if(!isVisited[neighbor]){
System.out.print(getValueByIndex(neighbor)+"->");
isVisited[neighbor] = true;
queue.addLast(neighbor);
}
/* Already visited */
neighbor = getNextNeighbor(u,neighbor);
}
}
}
/** * heavy load bfs * Let all vertices be traversed by breadth first */
public void bfs(){
for (int i = 0; i < getNumOfVertex(); i++) {
if (!isVisited[i]){
bfs(isVisited,i);
}
}
}
public static void main(String[] args) {
String[] vertexs = {
"A","B","C","D","E"};
/* Create a graph object */
Graph graph = new Graph(vertexs.length);
/* Add vertex */
for (String vertex:vertexs) {
graph.insertVertex(vertex);
}
/* Add edge */
graph.insertEdges(0,1,1);
graph.insertEdges(0,2,1);
graph.insertEdges(1,2,1);
graph.insertEdges(1,3,1);
graph.insertEdges(1,4,1);
System.out.println(" Breadth first traversal ");
graph.bfs();
}
Running results
Breadth first traversal
A->B->C->D->E
Process finished with exit code 0
边栏推荐
- 在Pi和Jetson nano上运行深度网络,程序被Killed
- guava: Multiset的使用
- The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends
- 记一次清理挖矿病毒的过程
- Leetcode topic [array] -118 Yang Hui triangle
- VIM basic configuration and frequently used commands
- In JS, string and array are converted to each other (II) -- the method of converting array into string
- @GetMapping、@PostMapping 和 @RequestMapping详细区别附实战代码(全)
- @Detailed differences among getmapping, @postmapping and @requestmapping, with actual combat code (all)
- Search map website [quadratic] [for search map, search fan, search book]
猜你喜欢
![[Digital IC manual tearing code] Verilog automatic beverage machine | topic | principle | design | simulation](/img/75/c0656c4890795bd65874b4f2b16462.jpg)
[Digital IC manual tearing code] Verilog automatic beverage machine | topic | principle | design | simulation

guava:Collections. The collection created by unmodifiablexxx is not immutable
![[interpretation of the paper] machine learning technology for Cataract Classification / classification](/img/0c/b76e59f092c1b534736132faa76de5.png)
[interpretation of the paper] machine learning technology for Cataract Classification / classification
![[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)](/img/1c/973f824f061d470a4079487d75f0d0.png)
[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)

It's not my boast. You haven't used this fairy idea plug-in!

爬虫实战(五):爬豆瓣top250

Dialogue with Jia Yangqing, vice president of Alibaba: pursuing a big model is not a bad thing

jvm:大对象在老年代的分配

【力扣刷题】一维动态规划记录(53零钱兑换、300最长递增子序列、53最大子数组和)

美国科技行业结束黄金时代,芯片求售、裁员3万等哀声不断
随机推荐
1292_FreeROS中vTaskResume()以及xTaskResumeFromISR()的实现分析
Forward maximum matching method
Seven original sins of embedded development
Efficiency tool +wps check box shows the solution to the sun problem
Sequoia China, just raised $9billion
通过数字电视通过宽带网络取代互联网电视机顶盒应用
One line by line explanation of the source code of anchor free series network yolox (a total of ten articles, you can change the network at will after reading it, if you won't complain to me)
Acdreamoj1110 (multiple backpacks)
在Pi和Jetson nano上运行深度网络,程序被Killed
代理和反向代理
JS operation DOM element (I) -- six ways to obtain DOM nodes
嵌入式开发的7大原罪
Fzu 1686 dragon mystery repeated coverage
JS get array subscript through array content
20220211 failure - maximum amount of data supported by mongodb
Z function (extended KMP)
Binary tree node at the longest distance
[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)
【滑动窗口】第九届蓝桥杯省赛B组:日志统计
分糖果