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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
思路:
每遇到’1’后, 开始向四个方向递归搜索。搜到后变为’0’, 因为相邻的属于一个island。然后开始继续找下一个’1’。
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == '1') {
search(grid, i, j);
++count;
}
}
}
return count;
}
private void search(char[][] grid, int x, int y) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] != '1')
return;
grid[x][y] = '0';
search(grid, x - 1, y);
search(grid, x + 1, y);
search(grid, x, y - 1);
search(grid, x, y + 1);
}
}
class Solution {
public int numIslands(char[][] grid) {
int count =0;
for (int i=0; i< grid.length; i++){
for (int j=0; j< grid[i].length;j++){
if (grid[i][j] == '1'){
count++;
dfs(grid, i, j);
}
}
}
return count;
}
void dfs (char[][] grid, int row, int col){
if (row> grid.length-1 || row<0 || col > grid[row].length-1|| col<0|| grid[row][col] == '0')
return ;
grid[row][col] = '0';
dfs(grid, row-1, col);
dfs(grid, row+1, col);
dfs(grid, row, col-1);
dfs(grid, row, col+1);
}
}
class Solution {
private static int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // up, down, right, left
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int counter = 0;
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid[i].length; j++){
if (grid[i][j] == '1') {
dfs(grid, i, j);
counter++;
}
}
}
return counter;
}
private static void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] == '0') return;
grid[i][j] = '0'; // mark as visited
for (int[] dir : directions) {
dfs(grid, i + dir[0], j + dir[1]);
}
}
}