LeetCode200 Number of Islands
问题来源 LeetCode200
问题描述
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”的方格内的元素的四周是否也为“1”,很明显会产生重复判断造成死循环,所以使用动态规划,维护一个和char[][]数组相同的数组来记录哪些为“1”的点是已经判断过的。
算法过程如下图:
这里需要注意的一点是,因为题中需要的是独立的岛的个数,所以需要维护一个全局变量,来保存。我们可以认为一次完成一次递归就代表遍历了一个岛屿,所以每次找到新的小岛,就进行累加。完成统计
具体代码如下
代码
int res =0;
public int numIslands(char[][] grid) {
if(grid==null||grid.length<1||grid[0].length<1) return 0;
int m =grid.length,n = grid[0].length;
boolean[][] dp = new boolean[m][n];
for (int i = 0; i <m ; i++) {
for (int j = 0; j <n ; j++) {
if(!dp[i][j]&&grid[i][j]=='1'){
help(grid,dp,i,j);
res++;
}
}
}
return res;
}
void help(char[][] grid,boolean[][] dp,int i,int j){
if(dp[i][j]) return;
if(grid[i][j]=='1'){
dp[i][j]=true;
if(i>0) help(grid,dp,i-1,j);
if(j>0) help(grid,dp,i,j-1);
if(i<grid.length-1) help(grid,dp,i+1,j);
if(j<grid[0].length-1) help(grid,dp,i,j+1);
}
}
LeetCode学习笔记持续更新
GitHub地址 https://github.com/yanqinghe/leetcode
优快云博客地址 http://blog.youkuaiyun.com/yanqinghe123/article/category/7176678