1
+ package problemsolving ;
2
+
3
+ /**
4
+ * Test
5
+ */
6
+ public class IsLands {
7
+
8
+ private static int countIslands = 0 ;
9
+ private static int adjRow [] = { -1 , 0 , 1 , 0 };
10
+ private static int adjCol [] = { 0 , 1 , 0 , -1 };
11
+
12
+ public static Boolean isSatify (int nr , int nc , int rows , int cols , int matrix [][]) {
13
+ if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && matrix [nr ][nc ] == 1 )
14
+ return true ;
15
+ return false ;
16
+ }
17
+
18
+ public static void findIslandsUtil (int matrix [][], int rows , int cols , int cr , int cc ) {
19
+ if (matrix [cr ][cc ] != 1 )
20
+ return ;
21
+ matrix [cr ][cc ] = -1 ;
22
+ for (int i = 0 ; i < adjRow .length ; i ++) {
23
+ int nr = cr + adjRow [i ];
24
+ int nc = cc + adjCol [i ];
25
+ if (isSatify (nr , nc , rows , cols , matrix ))
26
+ findIslandsUtil (matrix , rows , cols , nr , nc );
27
+ }
28
+
29
+ }
30
+
31
+ public static void findIslands (int matrix [][]) {
32
+ for (int i = 0 ; i < matrix .length ; i ++) {
33
+ for (int j = 0 ; j < matrix [i ].length ; j ++) {
34
+ if (matrix [i ][j ] == 1 )
35
+ countIslands ++;
36
+ findIslandsUtil (matrix , matrix .length , matrix [i ].length , i , j );
37
+ }
38
+ }
39
+
40
+ }
41
+
42
+ public static void main (String [] args ) {
43
+ int matrix [][] = {
44
+ { 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0 },
45
+ { 1 , 0 , 0 , 1 , 0 , 1 , 1 , 1 },
46
+ { 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 }
47
+ };
48
+ findIslands (matrix );
49
+ System .out .println ("Number of Islands = " + countIslands );
50
+ }
51
+ }
0 commit comments