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
求被0围起来的1的个数,连起来的1算一个
每遇到一个1就把周围的1全部置为0;
public class Solution { public int numIslands(char[][] grid) { int row = grid.length; if (row == 0){ return 0; } int col = grid[0].length; if (col == 0){ return 0; } int result = 0; for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ if (grid[i][j] == '1'){ setGrid(grid, i, j); result++; } } } return result; } public void setGrid(char[][] grid, int row, int col){ if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length) return ; if (grid[row][col] == '1'){ grid[row][col] = '0'; setGrid(grid, row - 1, col); setGrid(grid, row + 1, col); setGrid(grid, row, col + 1); setGrid(grid, row, col - 1); } } }