Given a 2d grid map ‘1‘
of S (land) ‘0‘
and S (water), count the number of islands. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
1 Public classSolution {2 Public intNumislands (Char[] grid) {3 if(Grid = =NULL|| Grid.length = = 0 | | Grid[0].length = = 0)return0;4 intm = grid.length, n = grid[0].length; 5 Boolean[] Visit =New Boolean[m][n];6 intAns = 0;7 for(inti = 0; I < m;i++){8 for(intj = 0; J < N; J + +){9 if(Visit[i][j]! =true&& Grid[i][j] = = ' 1 '){Tenans++; One BFS (visit,grid,i,j); A } - } - } the returnans; - } - - Public voidBFS (Boolean[] Visit,Char[] Grid,intRowintCol) { + if(Row >=0 && row < visit.length && Col >=0 && Col < visit[0].length -&& Visit[row][col]! =true&& Grid[row][col] = = ' 1 '){ +Visit[row][col] =true; ABFS (Visit,grid,row-1,col);//Up or down atBFS (visit,grid,row+1, col); -BFS (visit,grid,row,col-1); -BFS (visit,grid,row,col+1); - } - } -}
Number of Islands Java solutions