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
Public classSolution { Public intNumislands (Char[] grid) { //Dfs thought that when a node is found to be 1 o'clock, all nodes adjacent to it need to be set to 0, and this method will change the value of the original grid. if(grid==NULL|| grid.length<=0)return0; introw=grid.length; intCol=grid[0].length; intCount=0; for(inti=0;i<row;i++){ for(intj=0;j<col;j++){ if(grid[i][j]== ' 1 ') {Count++; DFS (GRID,I,J); } } } returncount; } Public voidDfsChar[] Grid,intIintj) { if(i<0| | i>grid.length-1| | j<0| | J>GRID[0].LENGTH-1)return; if(grid[i][j]== ' 1 ') {Grid[i][j]= ' 0 '; DFS (Grid,i-1, J); DFS (Grid,i+1, J); DFS (Grid,i,j-1); DFS (Grid,i,j+1); } }}
[Leedcode 200] Number of Islands