200岛屿数量
题目:给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
思路:这类题仍旧是DFS范畴的题型,因此,大体框架是不变的。 (terminator – process current level ---- drill down)。对于 drill down,对于二叉树,那就是进入 左右子树, 对于 多叉树那就是利用for
遍历子节点,对于本提的话,就是遍历当前点的上下左右四个方向
,以下为深度遍历的两种写法,我比较喜欢第一种~
解法一 深度优先遍历I
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
for (int i = 0; i < grid.size(); i++){
for (int j = 0; j < grid[0].size(); j++){
if (grid[i][j] == '1'){
helper(grid, i, j);
res++;
}
}
}
return res;
}
void helper(vector<vector<char>>& grid, int x, int y){
if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == '0') return;
grid[x][y] = '0';
helper(grid, x + 1, y);
helper(grid, x - 1, y);
helper(grid, x, y + 1);
helper(grid, x, y - 1);
}
};
解法二 深度优先遍历II
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
for (int i = 0; i < grid.size(); i++){
for (int j = 0; j < grid[0].size(); j++){
if (grid[i][j] == '1'){
helper(grid, i, j);
res++;
}
}
}
return res;
}
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void helper(vector<vector<char>>& grid, int x, int y){
if (grid[x][y] == '0') return;
grid[x][y] = '0';
for (int z = 0; z < 4; z++){
int newx = x + d[z][0];
int newy = y + d[z][1];
if (newx >= 0 && newx < grid.size() && newy >= 0 && newy < grid[0].size()){
helper(grid, newx, newy);
}
}
}
};