当前位置:网站首页>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
边栏推荐
- 语谱图怎么看
- [redis design and implementation] part I: summary of redis data structure and objects
- Yuan Xiaolin: safety is not only a standard, but also Volvo's unchanging belief and pursuit
- 【Redis设计与实现】第一部分 :Redis数据结构和对象 总结
- 数字化转型挂帅复产复工,线上线下全融合重建商业逻辑
- Uni app app half screen continuous code scanning
- FZU 1686 龙之谜 重复覆盖
- Sdl2 source analysis 7: performance (sdl_renderpresent())
- Redistemplate common collection instructions opsforlist (III)
- Proxy and reverse proxy
猜你喜欢
uni-app App端半屏连续扫码
跨分片方案 总结
guava:Collections. The collection created by unmodifiablexxx is not immutable
华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
抖音將推獨立種草App“可頌”,字節忘不掉小紅書?
20220211 failure - maximum amount of data supported by mongodb
Why rdd/dataset is needed in spark
Yuan Xiaolin: safety is not only a standard, but also Volvo's unchanging belief and pursuit
Quick news: the flybook players' conference is held online; Wechat payment launched "education and training service toolbox"
中国白酒的5场大战
随机推荐
SDL2来源分析7:演出(SDL_RenderPresent())
numpy 下载安装
Guava: three ways to create immutablexxx objects
Proxy and reverse proxy
20220211 failure - maximum amount of data supported by mongodb
JS traversal array and string
一行代码可以做些什么?
Quick news: the flybook players' conference is held online; Wechat payment launched "education and training service toolbox"
C# 如何在dataGridView里设置两个列comboboxcolumn绑定级联事件的一个二级联动效果
c语言char, wchar_t, char16_t, char32_t和字符集的关系
JS method to stop foreach
Sql: stored procedures and triggers - Notes
【力扣刷题】32. 最长有效括号
uni-app App端半屏连续扫码
El table table - sortable sorting & disordered sorting when decimal and% appear
袁小林:安全不只是标准,更是沃尔沃不变的信仰和追求
[go][reprint]vscode run a HelloWorld example after configuring go
Numpy download and installation
Technology sharing | packet capturing analysis TCP protocol
Z function (extended KMP)