試題
Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
代碼
一個島嶼是無規則的,但是我們可以把當前的島嶼給mask掉,這樣就不會影響下一個島嶼的統計。
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
if(grid.length == 0 || grid[0].length == 0) return count;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j] == '1'){
count++;
maskAll(grid, i, j, row, col);
}
}
}
return count;
}
public void maskAll(char[][] grid, int i, int j, int row, int col){
if(grid[i][j] == '0'){
return;
}
grid[i][j] = '0';
if(i-1 >= 0){
maskAll(grid, i-1, j, row, col);
}
if(i+1 < row){
maskAll(grid, i+1, j, row, col);
}
if(j-1 >= 0){
maskAll(grid, i, j-1, row, col);
}
if(j+1 < col){
maskAll(grid, i, j+1, row, col);
}
return;
}
}