Leetcode-542-01 Matrix

Posted zhang--yd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode-542-01 Matrix相关的知识,希望对你有一定的参考价值。

Leetcode-542-01 Matrix

542. 01 Matrix

  • Total Accepted: 1502
  • Total Submissions: 4775
  • Difficulty: Medium
  • Contributors: Stomach_ache

 

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0

 

Example 2: 
Input:

0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1

 

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

 

 

Subscribe to see which companies asked this question.

 

 

题解:

   经典的使用BFS的方法。 

 

 

class Solution {
public:
    const int dx[4] = {0, 0, -1, 1}; 
    const int dy[4] = {1, -1, 0, 0}; 
    
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        if(matrix.size() == 0 || matrix[0].size()==0){
            vector<vector<int> > ans; 
            return ans; 
        }
        int row = matrix.size(), colum = matrix[0].size(); 
        
        vector<vector<int> > ans(row, vector<int>(colum, 0)); 
        
        queue<pair<int,int>> seq; 
        vector<vector<int> > vis(row, vector<int>(colum, 0)); 
        for(int i=0; i<row; ++i){
            for(int j=0; j<colum; ++j){
                if(matrix[i][j] == 1){
                    if((i>0 && matrix[i-1][j]==0) || (i+1<row && matrix[i+1][j]==0) || 
                        (j>0 && matrix[i][j-1]==0)|| (j+1<colum && matrix[i][j+1]==0) ){
                            seq.push(make_pair(i, j)); 
                            ans[i][j] = 1; 
                            vis[i][j] = 1; 
                        }
                }
            }
        }
        
        int x, y, tmp_x, tmp_y; 
        while(!seq.empty()){
            x = seq.front().first; y = seq.front().second; 
            seq.pop(); 
            for(int i=0; i<4; ++i){
                tmp_x = dx[i] + x; tmp_y = dy[i] + y; 
                if(tmp_x >=0 && tmp_x <row && tmp_y >=0 && tmp_y < colum && matrix[tmp_x][tmp_y] == 1 && vis[tmp_x][tmp_y]==0){
                    ans[tmp_x][tmp_y] = ans[x][y] + 1; 
                    vis[tmp_x][tmp_y] = 1; 
                    seq.push(make_pair(tmp_x, tmp_y)); 
                }
            }
        }
        
        return ans; 
    }
};

  

 



以上是关于Leetcode-542-01 Matrix的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 542. 01 Matrix

leetcode 542. 01 Matrix 01 矩阵(中等)

leetcode542 01 Matrix

LeetCode542. 01 Matrix

[LeetCode] 542. 01 Matrix

[leetcode] 542. 01 Matrix (Medium)