Re: [闲聊] 每日LeetCode

楼主: idiont (supertroller)   2023-02-10 15:55:30
1162. As Far from Land as Possible
给一个 n*n 的 01 矩阵,
0 代表水池,1 代表陆地,
找到一块水池距离最近陆地的曼哈顿距离最远,
若无水池或陆地则回传 -1。
Example 1:
Input:
101
000
101
Output:
2
Explanation: 正中间的水池离最近的陆地距离为2
Example 2:
Input:
100
000
000
Output:
4
Explanation: 最右下水池离最左上的陆地距离为4
解题思路:
记录每一格离最近的陆地的距离,原本是陆地的设为0,原本是水池的设为无限大,
将每一个陆地都加入 queue 进行多源 BFS,每次更新上下左右四个位置,
由于是多源同时进行 BFS,距离只会非严格递增,不会有重复更新的问题,
最后看所有距离的最大值,0代表无水池,无限大代表无陆地,两者皆回传-1,
其余数值直接回传就是答案。
C++ Code:
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int, int>> que;
vector<vector<int>> dis(grid.size(), vector<int>(grid[0].size()));
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == 1) que.push({i, j});
else dis[i][j] = INT_MAX;
}
}
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
while(que.size() > 0){
auto front = que.front(); que.pop();
for(int i = 0; i < 4; i++){
int nx = front.first + dx[i];
int ny = front.second + dy[i];
if(nx >= 0 && nx < grid.size() && ny >= 0 && ny < grid[0].size()
&& dis[front.first][front.second] + 1 < dis[nx][ny]){
dis[nx][ny] = dis[front.first][front.second] + 1;
que.push({nx, ny});
}
}
}
int ans = 0;
for(auto i : dis){
for(auto j : i){
ans = max(ans, j);
}
}
return (ans == 0 || ans == INT_MAX) ? -1 : ans;
}
};
作者: pandix (面包屌)   2023-02-10 15:59:00
大师
作者: MurasakiSion (紫咲シオン)   2023-02-10 16:01:00
大师
作者: a9486l (a9486l)   2023-02-10 16:12:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com