-
Notifications
You must be signed in to change notification settings - Fork 1
/
200. Number of Islands.java
46 lines (38 loc) · 1.21 KB
/
200. Number of Islands.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
//OPTIMISED SOLUTION - O(m x n)
class Solution {
public int numIslands(char[][] grid) {
if(grid.length==0 || grid[0].length==0)
{
return 0;
}
int res =0;
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(grid[i][j]=='1')
{
res = res+1;
recrusive_dfs(grid, i,j);
}
}
}
return res;
}
//DFS
//O(m x n)
// this code will change the value of the grid to 0 if it is 1 and will also change the value of the neighbouring 1's to 0
public static void recrusive_dfs(char[][] grid , int row, int column)
{
//base case - this will be called when the row or column is out of bounds or the value is 0
if(row<0 || column<0 || row>=grid.length || column>= grid[0].length || grid[row][column]=='0')
{
return;
}
grid[row][column] = '0';
recrusive_dfs(grid, row-1, column);
recrusive_dfs(grid, row, column-1);
recrusive_dfs(grid, row+1, column);
recrusive_dfs(grid, row, column+1);
}
}