LeetCode刷题实战200:岛屿数量
Given an m x n 2d grid map of '1's (land) and '0's (water), return 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.
题意
示例
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
解题
class Solution {
public int numIslands(char[][] grid) {
int cnt = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == '1') {
depthSearch(grid,i,j);
cnt++;
}
}
}
return cnt;
}
public void depthSearch(char[][] grid, int i, int j) {
if (grid == null ||(i<0 || i >= grid.length) ||( j<0 || j >= grid[i].length)) {
return;
}
if (grid[i][j] != '1') {
return;
}
grid[i][j] = '0';
depthSearch(grid, i + 1, j) ;
depthSearch(grid, i - 1, j) ;
depthSearch(grid, i, j + 1) ;
depthSearch(grid, i, j - 1);
}
}