Skip to content

Commit a5f5817

Browse files
authored
Update Number of Closed Islands.java
1 parent 4b673d8 commit a5f5817

File tree

1 file changed

+29
-21
lines changed

1 file changed

+29
-21
lines changed

Medium/Number of Closed Islands.java

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,39 @@ class Solution {
22
private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
33

44
public int closedIsland(int[][] grid) {
5-
int numberOfClosedIslands = 0;
6-
for(int i = 0; i < grid.length; i++){
7-
for(int j = 0; j < grid[0].length; j++){
8-
if(grid[i][j] == 0){
9-
if(surroundsSuccessfully(grid, i, j)) {
10-
numberOfClosedIslands++;
11-
}
5+
int closedIslandCount = 0;
6+
for (int i = 0; i < grid.length; i++) {
7+
for (int j = 0; j < grid[0].length; j++) {
8+
if (grid[i][j] == 0 && isSurroundedSuccessfully(grid, i, j)) {
9+
closedIslandCount++;
1210
}
1311
}
1412
}
15-
return numberOfClosedIslands;
13+
return closedIslandCount;
1614
}
17-
18-
private boolean surroundsSuccessfully(int[][] grid, int x, int y) {
19-
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
20-
return false;
21-
}
22-
if(grid[x][y] == 1) {
23-
return true;
24-
}
25-
grid[x][y] = 1;
26-
boolean result = true;
27-
for(int[] dir : DIRS){
28-
result = result & surroundsSuccessfully(grid, x + dir[0], y + dir[1]);
15+
16+
private boolean isSurroundedSuccessfully(int[][] grid, int i, int j) {
17+
Queue<int[]> queue = new LinkedList<>();
18+
queue.add(new int[]{i, j});
19+
boolean surroundingCheck = true;
20+
while (!queue.isEmpty()) {
21+
int[] removed = queue.remove();
22+
int x = removed[0];
23+
int y = removed[1];
24+
if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length) {
25+
surroundingCheck = false;
26+
continue;
27+
}
28+
if (grid[x][y] == 1) {
29+
continue;
30+
}
31+
grid[x][y] = 1;
32+
for (int[] dir : DIRS) {
33+
int newX = x + dir[0];
34+
int newY = y + dir[1];
35+
queue.add(new int[]{newX, newY});
36+
}
2937
}
30-
return result;
38+
return surroundingCheck;
3139
}
3240
}

0 commit comments

Comments
 (0)