-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountNumberOfIsland.java
More file actions
48 lines (42 loc) · 1.58 KB
/
Copy pathcountNumberOfIsland.java
File metadata and controls
48 lines (42 loc) · 1.58 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
public class countNumberOfIsland {
static int[] moveX = {-1, -1, 0, 1, 1, 1, -1, 0}, moveY = {0, 1, 1, 1, 0, -1, -1, -1};
static int Rows, Cols;
public static void main(String[] args) {
int[][] islandGrid = new int[][]{
{1, 0, 1, 0, 0, 0, 1, 1, 1, 1},
{0, 0, 1, 0, 1, 0, 1, 0, 0, 0},
{1, 1, 1, 1, 0, 0, 1, 0, 0, 0},
{1, 0, 0, 1, 0, 1, 0, 0, 0, 0},
{1, 1, 1, 1, 0, 0, 0, 1, 1, 1},
{0, 1, 0, 1, 0, 0, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 1, 0, 0, 1, 1, 1, 0},
{1, 0, 1, 0, 1, 0, 0, 1, 0, 0},
{1, 1, 1, 1, 0, 0, 0, 1, 1, 1}
};
Rows = islandGrid.length;
Cols = islandGrid[0].length;
System.out.println("No of Islands: " + countNumberOfIsland.numIslands(islandGrid));
}
public static int numIslands(int[][] islandGrid) {
if (Rows == 0) return 0;
int result = 0;
for (int i = 0; i < Rows; i++) {
for (int j = 0; j < Cols; j++) {
if (islandGrid[i][j] == 1) {
DFS(islandGrid, i, j);
result++;
}
}
}
return result;
}
public static void DFS(int[][] islandGrid, int row, int col) {
if (row < 0 || col < 0 || row >= Rows || col >= Cols || islandGrid[row][col] != 1)
return;
islandGrid[row][col] = 0;
for (int i = 0; i < 8; i++) {
DFS(islandGrid, row + moveX[i], col + moveY[i]);
}
}
}