【leetcode】200. Number of Islands

题目:
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.


思路:
只要找到一个为“1”的点,就从这个点开始深度优先遍历,把所有连接在一起的“1”点都置0。然后重复前述操作。每操作一次,就是操作的一个岛屿。


代码实现:

class Solution {
public:
    bool checkCoord(vector<vector<char>>& grid, int r, int c){
        int rows = grid.size();
        int cols = grid[0].size();
        if (r >= 0 && r < rows && c >= 0 && c < cols){
            return true;
        }
        return false;
    }
    void f(vector<vector<char>>& grid, int r, int c){
        if (checkCoord(grid, r, c) && grid[r][c] == '1'){
            grid[r][c] = '0';
            f(grid, r-1, c);
            f(grid, r+1, c);
            f(grid, r, c-1);
            f(grid, r, c+1);
        }
        return ;
    }
    
    
    int numIslands(vector<vector<char>>& grid) {
        int rows = grid.size();
        if (rows <= 0){
            return 0;
        }
        int cols = grid[0].size();
        int count = 0;
        for (int i = 0; i < rows; ++i){
            for (int j = 0; j < cols; ++j){
                if (grid[i][j] == '1'){
                    ++count;
                    f(grid, i, j);
                }
            }
        }
        
        return count;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值