Algorithm Notes - Depth/Breadth First Search

Algorithm Notes - Depth/Breadth First Search

Depth-first search and breadth-first search are mainly used in graph traversal. They are highly templated. I personally think they are relatively simple algorithms. The following are the templates for deep search and wide search. Follow the templates to do more questions. can master

depth-first search

Process:

  1. access the specified starting vertex
  2. If there are unvisited adjacent vertices of the currently visited vertex, select one of the vertices to visit, and then go back to the first step
  3. If all adjacent vertices of the current vertex have been visited, return the previous vertex of the current vertex

As shown in the figure below, in fact, it is to visit the end along one edge first, and then return to visit the other edge

template

DFS is generally implemented by recursion

 void dfs(int x){
    
    
    if (满足退出条件){
    
     
        退出处理
        return; 
    }
    for (;;){
    
    //枚举当前顶点的下一个邻接顶点
        if (顶点满足条件) {
    
    
            处理顶点
            dfs(顶点);//向下深入遍历
            }
    }
    return ;//退出 
}

Here, when enumerating the next adjacent vertex, if it is in the graph, I used to define a direction vector first, and then use this to enumerate the next vertex
. Take the four directions of up, down, left and right as an example:
First define:

 int fx[4][2] = {
    
    {
    
    -1, 0}, {
    
    0, 1}, {
    
    1, 0}, {
    
    0, -1}};

enumerate:

for (int i = 0; i < 4; i++)
{
    
    
   dfs(x + fx[i][0], y + fx[i][1], board);
}

Breadth-first search

Process:

  1. access the specified starting vertex
  2. enqueue all adjacent vertices of a vertex
  3. Return to the first element of the first access queue, and the first element of the queue pops up

As shown in the figure below, first add the adjacent vertices of the current vertex to the queue, and then access the adjacent vertices of the next layer
insert image description here

template

BFS is generally implemented through queues

		queue<int> qu;//定义队列
        qu.push(起始顶点);
        while (!qu.empty())
        {
    
    
            auto front = qu.front();
            qu.pop();
            //获得首部顶点并将首部弹出

            for (;;)//遍历当前顶点的所有邻接顶点并加入队列
            {
    
    
                if (邻接顶点符合题目要求)
                {
    
    
                    qu.push(邻接顶点);
                }
            }
        }

The above template is only the most basic example. Different topics will definitely be different. You need to make further modifications based on the template and the meaning of the question.

example

1091. Shortest Path in Binary Matrix
130. Surrounded Area

Guess you like

Origin blog.csdn.net/shn111/article/details/123313243