Leikou problem solution: 542 problem 01 matrix knowledge points: multi-source BFS (determine the current traversal level or not two types of templates) used to find the shortest distance

1. Title description: title link
Given a matrix consisting of 0 and 1, find out the distance between each element and the nearest 0.
The distance between two adjacent elements is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Note:
The number of elements in the given matrix does not exceed 10,000.
At least one element in the given matrix is ​​0.
The elements in the matrix are only adjacent in four directions: up, down, left, and right.

2. Idea: Understand what the topic is to investigate, the remaining task is to set the template!
a) First seeSearch the distance on the matrix and think about the solution of the graph.
b) This question gives a scenario: find the shortest distance from 1 to 0.In a graph, the method to find the shortest distance from a point is easy to think of as BFS, That is, after searching the surrounding circle, search for the next circle, which is to slowly expand the search range.

2.1. BFS template:
BFS uses a queue, puts each point that has not been searched into the queue in turn, and then pops the head element of the queue as the current traverse point. BFS has two templates in total:
a) If there is no need to determine which level is currently traversed, the BFS template is as follows:

while queue 不空:
    cur = queue.pop()
    for 节点 in cur的所有相邻节点:
        if 该节点有效且未访问过:
            queue.push(该节点)

b) If you want to determine which layer is currently traversed, the BFS template is as follows:
hereAdded level indicates which level of the binary tree is currently traversed. It can also be understood as how many steps have been taken in a graph.. The size indicates how many elements are in the current traversal layer, that is, the number of elements in the queue. We traverse these elements at once, that is, take all the elements of the current layer one step outward.

level = 0
while queue 不空:
    size = queue.size() // 记录当前层次
    while (size --) {
    
    
        cur = queue.pop()
        for 节点 in cur的所有相邻节点:
            if 该节点有效且未被访问过:
                queue.push(该节点)
    }
    level ++;

The above two are general templates, which can be used in any topic, just remember!
Link ideas, author: fuxuemingzhu

3. The difference between multi-source BFS and single-source BFS:
3.1. Ideas:

  • for "Tree's BFS" (typical "single source BFS")Everyone is already familiar with the
    road : first enter the root node into the team, and then traverse layer by layer without thinking.
  • for "Graphic BFS" ("Multi-source BFS"), And the difference between "Tree's BFS" pay attention to the following two:
    Tree has only 1 root, and the graph can have multiple sources, soFirst, you need to enqueue multiple sources;
    Tree is directed so there is no need to identify whether it has been visited, andFor undirected graphs, it is necessary to mark whether they have been visited! And in order to prevent a certain node from entering the team multiple times, it needs to be set as visited before it enters the team!
    Link ideas, author: sweetiee

3.2. Source search:

  • For Tree: The
    source point is the root of the tree.
  • For graphs:
    the traversal of graphs can start at any point, butFor multi-source problems, first traverse all vertices to find out all the source points are pushed into the queue.

4. C++ code: The
code is to record your own thoughts, and the time complexity and space complexity are not optimal. For the optimal code, see the two links above.

class Solution {
    
    
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
    
    
        int row = matrix.size();
        int col = matrix[0].size();
        vector<vector<int>> res(row,vector<int>(col)); //记录结果
        vector<vector<int>> visited(row,vector<int>(col)); // 记录访问情况
        queue<pair<int,int>> q;
        for(int i = 0;i<row; i++){
    
     //首先查找所有源点
            for(int j = 0;j<col; j++){
    
    
                if(matrix[i][j] == 0){
    
                       
                    q.push(make_pair(i,j));
                    visited[i][j] = 1;
                }
            }
        }
        int val = 0; // 记录遍历层次
        while(!q.empty()){
    
    
            int size = q.size(); //记录每一层元素个数
            for(int i = 0;i<size;i++){
    
    
                pair<int, int> tmp = q.front();
                q.pop();
                res[tmp.first][tmp.second] = val;
                if(tmp.first-1>=0 && visited[tmp.first-1][tmp.second] == 0){
    
    
                    q.push(make_pair(tmp.first-1,tmp.second));
                    visited[tmp.first-1][tmp.second] = 1;
                }
                if(tmp.first+1<row && visited[tmp.first+1][tmp.second] == 0){
    
    
                    q.push(make_pair(tmp.first+1,tmp.second));
                    visited[tmp.first+1][tmp.second] = 1;
                }
                if(tmp.second-1>=0 && visited[tmp.first][tmp.second-1] == 0){
    
    
                    q.push(make_pair(tmp.first,tmp.second-1));
                    visited[tmp.first][tmp.second-1] = 1;
                }
                if(tmp.second+1<col && visited[tmp.first][tmp.second+1] == 0){
    
    
                    q.push(make_pair(tmp.first,tmp.second+1));
                    visited[tmp.first][tmp.second+1] = 1;
                }
            }
            val++;
        }
        return res;
    }
};

to sum up:

1. Finding the distance is generally a problem of graphs. Think about the solution of graphs.
2. The shortest distance is usually solved by BFS.
3. Multi-source BFS first finds all source points.
4. Remember the above BFS method of determining the current traversal level.

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/106452806