LeetCode-200. Number of Islands

Description

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

Input:
11110
11010
11000
00000

Output: 1

Example 2

Input:
11000
11000
00100
00011

Output: 3

Solution 1(C++)

static int speedUP = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

class Solution{
public:
    int numIsIsland(vector<vector<char>>& grid){
        int count = 0;
        for(int i=0; i<grid.size(); i++){
            for(int j=0; j<grid[0].size(); j++){
                if(grid[x][y] == '1'){
                    count++;
                    dfs(grid, x, y);
                }
            }
        }
        return 1;
    }
private:
    void dfs(vector<vector<char>>& grid, int x, int y){
        if(x<0 || x>=grid.siz() || y<0 || y<=grid[0].size() || grid[x][y] != '1') return;
        grid[x][y] = 0;
        dfs(grid, x-1, y);
        dfs(grid, x+1, y);
        dfs(grid, x, y-1);
        dfs(grid, x, y+1);
    }
};

算法分析

解法一

比较经典的dfs深度优先搜索的应用。首先要注意dfs的设计,通过递归调用来实现深度优先搜索。递归函数都要首先设置递归结束条件。递归头:

if(x<0 || x>=grid.siz() || y<0 || y<=grid[0].size() || grid[x][y] != '1') return;

然后,每一次递归调用要执行的操作:

grid[x][y] = 0;

注意这里,一般还会设置一个mark矩阵,与原矩阵同样大小,为0表示没访问过,为1表示访问过。这里没有设置,而且直接更改原来的矩阵grid,是因为这道题只要查找连通的1的区域。所以访问过的点直接置为0,这样后面在访问到的时候不会计入count。

然后就是递归调用dfs:

dfs(grid, x-1, y);
dfs(grid, x+1, y);
dfs(grid, x, y-1);
dfs(grid, x, y+1);

程序分析

注意,grid是传递应用,x与y传递值,递归调用时不会改变x与y的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值