Topic:
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
Idea: Loop through the array, found a 1 to the left and right up and down all 1 are found and tagged, and the counter plus 1.
Code:
Public classSolution { Public intNumislands (Char[] grid) { intm =grid.length; if(M = = 0)return0; intn = grid[0].length; intCount = 0; for(inti = 0; I < m; i++){ for(intj = 0; J < N; J + +){ if(Grid[i][j] = = ' 1 '{replace (grid, I, j); Count++; } } } returncount; } Public voidReplaceChar[] Grid,intIintj) { intm =grid.length; intn = grid[0].length; GRID[I][J]= ' # '; if(j-1 >= 0 && grid[i][j-1] = = ' 1 ') Replace (grid, I, J-1); if(i-1 >= 0 && grid[i-1][j] = = ' 1 ') Replace (grid, I-1, J); if(I+1 < m && grid[i+1][j] = = ' 1 ') Replace (grid, I+1, J); if(J+1 < n && grid[i][j+1] = = ' 1 ') Replace (grid, I, J+1); return; }}
[Leetcode-java] Number of Islands