542. 01 矩阵
笔记 x*col+y这里卡了很久
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
row=matrix.size(), col=matrix[0].size();
vector<vector<int>> res(row);
for(int i=0;i<row;i++) res[i].resize(col);
fill(visited, visited+10005, false);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(matrix[i][j]==0) res[i][j]=0;
else res[i][j]=get_value(i, j, matrix, res);
}
}
return res;
}
private:
int row, col;
bool visited[10005];
vector<vector<int> > v = {{1,0},{-1,0},{0,1},{0,-1}};
int get_value(int x, int y, vector<vector<int>>& matrix, vector<vector<int>>& res){
queue<vector<int>> q;
q.push({x, y});
int step = 0;
while(!q.empty()){
int size = q.size();
while(size){
vector<int> t = q.front();
x=t[0];y=t[1];
if(matrix[x][y]==0){
visited[x*col+y]=true;
return step;
}
if(visited[x*col+y]==true){
return step+res[x][y];
}
q.pop();
for(int i=0;i<4;i++){
int nx = t[0]+v[i][0], ny=t[1]+v[i][1];
if(nx<row && ny <col && nx>=0 && ny>=0){
q.push({nx, ny});
}
}
size--;
}
step++;
}
return 0;
}
};