题目 矩形
给定一个由 0
和 1
组成的矩阵 mat
,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0
的距离。
两个相邻元素间的距离为 1
。
题解 广度优先搜索
本题的本质就是寻找离1
最近的0
,那么就可以从0
出发进行搜索,一开始利用一个队列把所有的0
都压入队列,并把1
的位置改为-1
表示未访问过。
如果遇到符合要求的:表示它为当前距离+1
if(pos_x >=0 && pos_x < row && pos_y >= 0 &&
pos_y < col && mat[pos_x][pos_y] == -1){
mat[pos_x][pos_y] = mat[x][y] + 1;
q.push(make_pair(pos_x, pos_y));
}
完整代码如下:
class Solution {
public:
const int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int row = mat.size();
int col = mat[0].size();
queue<pair<int, int>> q;
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(mat[i][j] == 0){
q.push(make_pair(i, j));
}
else{
mat[i][j] = -1;
}
}
}
while(!q.empty()){
auto [x, y] = q.front();
q.pop();
for(int i = 0; i < 4; ++i){
int pos_x = x + dir[i][0];
int pos_y = y + dir[i][1];
if(pos_x >=0 && pos_x < row && pos_y >= 0 && pos_y < col
&& mat[pos_x][pos_y] == -1){
mat[pos_x][pos_y] = mat[x][y] + 1;
q.push(make_pair(pos_x, pos_y));
}
}
}
return mat;
}
};
题目 地图分析
你现在手里有一份大小为 N x N
的 网格 grid,上面的每个 单元格 都用 0 和 1
标记好了。其中 0
代表海洋,1
代表陆地,请你找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距离是最大的。
我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0)
和 (x1, y1)
这两个单元格之间的距离是 |x0 - x1| + |y0 - y1|
。
如果网格上只有陆地或者海洋,请返回 -1
。
题解 广度优先搜索
上一题的本质是寻找离1最近的0,这一题刚好反过来,寻找离1最近的0的最远距离,则与上一题处理思路完全一样:
class Solution {
public:
const int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int, int>> q;
int row = grid.size();
int col = grid[0].size();
int cnt = 0;
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(grid[i][j] == 1){
q.push({i, j});
cnt++;
grid[i][j] = 0;
}
else{
grid[i][j] = -1;
}
}
}
if(cnt == 0 || cnt == row * col)
return -1;
int x, y;
while(!q.empty()){
x = q.front().first;
y = q.front().second;
q.pop();
for(int i = 0; i < 4; ++i){
int pos_x = x + dir[i][0];
int pos_y = y + dir[i][1];
if(pos_x >=0 && pos_x < row && pos_y >= 0 &&
pos_y < col && grid[pos_x][pos_y] == -1){
grid[pos_x][pos_y] = grid[x][y] + 1;
q.push({pos_x, pos_y});
}
}
}
//int res;
//for(int i = 0; i < row; ++i){
// res = max(res,*max_element(grid[i].begin(), grid[i].end()));
//}
return grid[x][y];
}
};
总结
多思考,多学习!