File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(n * m)
2
+ // retrieve all elemetns, grid.length * grid[0].length
3
+ // SC: O(n * m(
4
+ // need to change all elements from 1 to 0 in the worst case
5
+ class Solution {
6
+ int output = 0 ;
7
+ public int numIslands (char [][] grid ) {
8
+ for (int i = 0 ; i < grid .length ; i ++) {
9
+ for (int j = 0 ; j < grid [0 ].length ; j ++) {
10
+ if (grid [i ][j ] == '1' ) {
11
+ output += 1 ;
12
+ countIslands (i , j , grid );
13
+ }
14
+ }
15
+ }
16
+ return output ;
17
+ }
18
+
19
+ private void countIslands (int i , int j , char [][] grid ) {
20
+ if (i < 0 || i >= grid .length || j < 0 || j >= grid [0 ].length ) return ;
21
+ if (grid [i ][j ] == '0' ) return ;
22
+ grid [i ][j ] = '0' ;
23
+ countIslands (i +1 , j , grid );
24
+ countIslands (i -1 , j , grid );
25
+ countIslands (i , j +1 , grid );
26
+ countIslands (i , j -1 , grid );
27
+ }
28
+ }
You can’t perform that action at this time.
0 commit comments