当前位置:网站首页>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
边栏推荐
- JS learning notes OO create suspicious objects
- 华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
- [sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
- 快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
- PostgreSQL install GIS plug-in create extension PostGIS_ topology
- Nodejs tutorial let's create your first expressjs application with typescript
- Guava: use of multiset
- The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends
- Reptile practice (V): climbing watercress top250
- guava:创建immutableXxx对象的3种方式
猜你喜欢

50个常用的Numpy函数解释,参数和使用示例

50 commonly used numpy function explanations, parameters and usage examples

红杉中国,刚刚募资90亿美元
![[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

Absolute primes (C language)

美国科技行业结束黄金时代,芯片求售、裁员3万等哀声不断

Numpy download and installation

What can one line of code do?
![[redis design and implementation] part I: summary of redis data structure and objects](/img/2e/b147aa1e23757519a5d049c88113fe.png)
[redis design and implementation] part I: summary of redis data structure and objects

袁小林:安全不只是标准,更是沃尔沃不变的信仰和追求
随机推荐
Description of web function test
Four common ways and performance comparison of ArrayList de duplication (jmh performance analysis)
麦趣尔砸了小众奶招牌
中国白酒的5场大战
数字化转型挂帅复产复工,线上线下全融合重建商业逻辑
Search map website [quadratic] [for search map, search fan, search book]
Reptile practice (V): climbing watercress top250
SDL2来源分析7:演出(SDL_RenderPresent())
NPM run dev start project error document is not defined
It's not my boast. You haven't used this fairy idea plug-in!
[in depth learning] pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
红杉中国,刚刚募资90亿美元
npm run dev启动项目报错 document is not defined
Internet News: Geely officially acquired Meizu; Intensive insulin purchase was fully implemented in 31 provinces
爬虫实战(五):爬豆瓣top250
Vit paper details
Set up a time server
互联网快讯:吉利正式收购魅族;胰岛素集采在31省全面落地
50个常用的Numpy函数解释,参数和使用示例
Redistemplate common collection instructions opsforzset (VI)