-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNoOfIsland.java
55 lines (39 loc) · 1.41 KB
/
NoOfIsland.java
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
import java.util.Stack;
public class NoOfIsland {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int numIslands = 0;
int n = grid.length;
int m = grid[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
numIslands++;
iterativeDFS(grid, i, j, n, m);
}
}
}
return numIslands;
}
private void iterativeDFS(char[][] grid, int startX, int startY, int n, int m) {
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{startX, startY});
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
grid[startX][startY] = '0';
while (!stack.isEmpty()) {
int[] current = stack.pop();
int x = current[0];
int y = current[1];
for (int[] dir : directions) {
int newX = x + dir[0];
int newY = y + dir[1];
if (newX >= 0 && newX < n && newY >= 0 && newY < m && grid[newX][newY] == '1') {
grid[newX][newY] = '0';
stack.push(new int[]{newX, newY});
}
}
}
}
}