原题:
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
思路:题目提示是DFS,也就是递归解决问题,但是一时无法想到好的递归办法。后面参考了别人的代码,发现是需要做一层转换,当碰到'1'的时候,递归的把这个'1'及其周围的'1'都变成'0',这样就相当于消灭了一个island。于是乎有了下面的代码,其实还是很简单的哈,但是这个转换实在是没想到,以后要记住。
代码:
public class Solution {
public int numIslands(char[][] grid) {
int ret = 0;
for(int i=0;i<grid.length;i++) {
for(int j=0;j<grid[0].length;j++) {
if(grid[i][j] == '1') {
dfs(grid, i, j);
ret++;
}
}
}
return ret;
}
void dfs(char[][] grid, int i, int j) {
if(i<0 || i>= grid.length || j<0 || j>=grid[0].length || grid[i][j] != '1') return;
grid[i][j] = '0';
dfs(grid, i-1, j);
dfs(grid, i+1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
}
}