-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0463-island-perimeter.java
More file actions
58 lines (53 loc) · 1.86 KB
/
0463-island-perimeter.java
File metadata and controls
58 lines (53 loc) · 1.86 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
55
56
57
58
class Solution {
public int islandPerimeter(int[][] grid) {
int res = 0, n = grid.length, m = grid[0].length;
Queue<int []> q = new LinkedList<>();
boolean found = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) { //find the first cell with a 1
q.offer(new int[] {i ,j});
found = true;
break;
}
}
if (found) break;
}
while (!q.isEmpty()) { //BFS
int size = q.size();
for (int i = 0; i < size; i++) {
int[] curr = q.poll();
int x = curr[0], y = curr[1];
if (grid[x][y] == 2) continue;
grid[x][y] = 2; //mark as visited
//if neigh out of bounds or water, add 1 to res
if (x + 1 >= n || grid[x + 1][y] == 0) {
res++;
}
//otherwise if its another land, put it in the q
else if (grid[x + 1][y] == 1) {
q.offer(new int[]{x + 1, y});
}
if (x - 1 < 0 || grid[x - 1][y] == 0) {
res++;
}
else if (grid[x - 1][y] == 1) {
q.offer(new int[]{x - 1, y});
}
if (y + 1 >= m || grid[x][y + 1] == 0) {
res++;
}
else if (grid[x][y + 1] == 1) {
q.offer(new int[]{x, y + 1});
}
if (y - 1 < 0 || grid[x][y - 1] == 0) {
res++;
}
else if (grid[x][y - 1] == 1){
q.offer(new int[]{x, y - 1});
}
}
}
return res;
}
}