1162. As Far from Land as Possible

问题:

给定n*n二维数组,

0代表海水,1代表陆地,

求离陆地最远的海水cell,距离陆地多远。

Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.

Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
 
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] is 0 or 1

  

example 1:

 

 

example 2:

 

 

解法:BFS

状态:cell坐标+当前坐标访问过?grid==1?

扩展层数即为所求最远距离。

base:首先将陆地,grid=1的cell加入queue。

对于每个状态node:遍历上下左右四个节点:

在grid范围内&&grid==0(未访问过&&是海水),则入队。且标记访问grid=1。

 

代码参考:

 1 class Solution {
 2 public:
 3     int dir[5] = {1,0,-1,0,1};
 4     int maxDistance(vector<vector<int>>& grid) {
 5         queue<pair<int,int>> q;
 6         int n = grid.size();
 7         for(int i=0; i<n; i++) {
 8             for(int j=0; j<n; j++) {
 9                 if(grid[i][j]==1) {
10                     q.push({i,j});
11                 }
12             }
13         }
14         int step = 0;
15         if(q.size()==n*n) return -1;
16         while(!q.empty()) {
17             int sz = q.size();
18             for(int k=0; k<sz; k++) {
19                 auto [i,j] = q.front();
20                 q.pop();
21                 for(int d=1; d<5; d++) {
22                     int x = i+dir[d-1];
23                     int y = j+dir[d];
24                     if(x<0 || y<0 || x>=n || y>=n || grid[x][y] != 0) continue;
25                     q.push({x,y});
26                     grid[x][y]=1;
27                 }
28             }
29             step++;
30         }
31         return step-1;
32     }
33 };

 

posted @ 2021-03-14 13:44  habibah_chang  阅读(65)  评论(0编辑  收藏  举报