2021-3-8-深度遍历问题

题目描述

给一个01矩阵,1代表是陆地,0代表海洋, 如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
岛屿: 相邻陆地可以组成一个岛屿(相邻:上下左右) 判断岛屿个数。
输入:
[[1,1,0,0,0],[0,1,0,1,1],[0,0,0,1,1],[0,0,0,0,0],[0,0,1,1,1]]
输出:
3

class Solution {
public:
    /**
     * 判断岛屿数量
     * @param grid char字符型vector<vector<>> 
     * @return int整型
     */
    void dfs(int x, int y, const vector<vector<char> > &grid, vector<vector<bool> > &mark, int row, int col)
    {
        if (x < 0 || x >= row || y < 0 || y >= col || mark[x][y] == false) return;
        if (grid[x][y] == '1') {
            mark[x][y] = false;
            //上下左右搜索
            dfs(x - 1, y, grid, mark, row, col);
            dfs(x + 1, y, grid, mark, row, col);
            dfs(x, y - 1, grid, mark, row, col);
            dfs(x, y + 1, grid, mark, row, col);
        }
    }


    int solve(vector<vector<char> >& grid)
    {
        // write code here
        int row = grid.size();
        if (row == 0) return 0;
        int col = grid[0].size();
        int count = 0;

        vector<vector<bool> > mark(row, vector<bool>(col, true));
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
            	//如果当前位置为陆地,就深度搜索该位置
                if (grid[i][j] == '1' && mark[i][j] == true) {
                    dfs(i, j, grid, mark, row, col);
                    ++count;
                }
            }
        }

        return count;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值