Given a 2d grid map of
Example 1:
Example 2:
Solution
Its a Graph problem to find number of components. We can iterate through the matrix and check if current node is 1 or 0, If its 1 then explore surrounded elements and mark current node as 0.
Code
0 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 56 |
public class NumberOfIsland { int [] a={0,-1,0,1}; int [] b={1,0,-1,0}; public int numIslands(char[][] grid) { int l=grid.length; if(l==0) return 0; int m=grid[0].length,cnt=0; for(int i=0;i<l;i++){ for(int j=0;j<m;j++){ if(grid[i][j]=='1'){ cnt++; exploreGrid(grid,i,j,l,m); } } } return cnt; } public void exploreGrid(char[][] grid,int i,int j,int l,int m){ if(i<0 || j<0 || i>=l || j>=m) return ; if(grid[i][j]=='1'){ grid[i][j]='0'; for(int k=0;k<4;k++){ exploreGrid(grid,i+a[k],j+b[k],l,m); } } } public static void main(String[] args) { char [][] a= { {'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'}, {'0','0','0','1','1'} }; System.out.println(new NumberOfIsland().numIslands(a)); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.