题目
multi-source bfs问题
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size();
queue<pair<int,int>> q;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(grid[i][j] == 1){
q.push(make_pair(i,j));
grid[i][j] = 0;
}else{
grid[i][j] = -1;
}
}
}
vector<pair<int,int>> dirs{{0,1},{0,-1},{1,0},{-1,0}};
int ans = 0;
while(!q.empty()){
auto curr = q.front();
q.pop();
for(auto& d : dirs){
int x = curr.first + d.first;
int y = curr.second + d.second;
if(x < 0 || y < 0 || x >= n || y >= n || grid[x][y] != -1) continue;
q.push(make_pair(x,y));
grid[x][y] = grid[curr.first][curr.second]+1;
ans = max(ans,grid[x][y]);
}
}
return ans == 0 ? -1 : ans;
}
};
类似问题:
Leetcode 542. 01 Matrix
Leetcode 286. Walls and Gates