问题描述
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.
解题思路
题目给出一个0,1矩阵,找到矩阵中每个1距离0的最短路径,然后以矩阵的形式输出。典型的BFS(广度优先)问题求解,该题要注意溢出问题
代码块
class Solution {
private:
vector<vector<int>>visit,d;
queue<pair<int,int>>q;
pair<int,int>p;
int cur_i,cur_j;
int width,height;
void push_and_set(int row,int col){
if(row>=0&&row<height&&col>=0&&col<width&&!visit[row][col]){
d[row][col] = d[cur_i][cur_j] + 1;
visit[row][col] = 1;
q.push(make_pair(row,col));
}
}
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
height = matrix.size();
width = matrix[0].size();
visit = vector<vector<int>>(height,vector<int>(width));
d = vector<vector<int>>(height,vector<int>(width));
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
if(matrix[i][j] == 0){
q.push(make_pair(i,j));
visit[i][j]=1;
d[i][j] = 0;
}
}
}
while(!q.empty()){
p = q.front();
q.pop();
cur_i = p.first;
cur_j = p.second;
push_and_set(cur_i - 1, cur_j);
push_and_set(cur_i + 1, cur_j);
push_and_set(cur_i, cur_j + 1);
push_and_set(cur_i, cur_j - 1);
}
return d;
}
};