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
CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678