1162. As Far from Land as Possible

LeetCode

link
BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int maxDistance(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0)return -1;
Queue<int[]> queue = new ArrayDeque<>();
int countOf1=0;
for(int i = 0 ; i < grid.length ; i++) {
for(int j = 0 ; j < grid[0].length ; j++) {
if(grid[i][j] == 1) {
queue.offer(new int[]{i,j});
countOf1++;
}
}
}
if(countOf1==grid.length*grid[0].length) return -1;
int[][] directions = {{-1, 0},{1,0},{0,-1},{0,1}};
int level = -1;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0 ; i < size ; i++) {
int[] start = queue.poll();
for(int[] dir : directions) {
int newX = start[0] + dir[0];
int newY = start[1] + dir[1];
if(newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length && grid[newX][newY] == 0){
grid[newX][newY] = 1;
queue.offer(new int[]{newX, newY});
}
}
}
level++;
}
return level;
}
}

0%