-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsFarFromLandAsPossible.java
More file actions
54 lines (46 loc) · 1.62 KB
/
AsFarFromLandAsPossible.java
File metadata and controls
54 lines (46 loc) · 1.62 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package graph;
import java.util.LinkedList;
import java.util.Queue;
/**
* Description: https://leetcode.com/problems/as-far-from-land-as-possible
* Difficulty: Medium
* Time complexity: O(m * n)
* Space complexity: O(m * n)
*/
public class AsFarFromLandAsPossible {
public int maxDistance(int[][] grid) {
int[][] visited = new int[grid.length][grid[0].length];
int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
Queue<int[]> planned = new LinkedList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
visited[i][j] = 1;
planned.offer(new int[]{i, j});
}
}
}
// no land cells or no water cells
if (planned.isEmpty() || planned.size() == grid.length * grid[0].length) {
return -1;
}
int distance = 0;
while (!planned.isEmpty()) {
int levelSize = planned.size();
distance++;
for (int i = 0; i < levelSize; i++) {
int[] current = planned.poll();
for (int[] dir : directions) {
int x = current[0] + dir[0];
int y = current[1] + dir[1];
if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length
&& visited[x][y] == 0) {
visited[x][y] = 1;
planned.offer(new int[]{x, y});
}
}
}
}
return distance - 1;
}
}