Leetcode-542-01 Matrix
542. 01 Matrix
Add to List
- 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 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
0 0 0 0 1 0 1 2 1
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- 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;
}
};