1020. Number of Enclaves

题目:

You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.

Example 2:

Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • grid[i][j] is either 0 or 1.

思路:

这题其实理解了什么是enclave就行了,其实就是不和矩形边界相连的地块。这样只要用dfs/bfs把与矩阵边界相邻的地块从1置为0,之后遍历矩阵,剩下的所有1就是飞地。本题用的是dfs,遍历4条边界的时候,如果当前格子为1,即这是陆地,则用dfs进行搜索并置0,最后遍历矩阵获得答案。

代码:

class Solution {
public:
    int numEnclaves(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        for (int i = 0 ; i < n; i++) {
            if (grid[0][i]) dfs(grid, 0, i);
            if (grid[m - 1][i]) dfs(grid, m - 1, i);
        }
        for (int j = 0; j < m; j++) {
            if (grid[j][0]) dfs(grid, j, 0);
            if (grid[j][n - 1]) dfs(grid, j, n - 1);
        }
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j])
                    count++;
            }
        }
        return count;
    }
private:
    void dfs(vector<vector<int>> &grid, int x, int y) {
        int m = grid.size(), n = grid[0].size();
        if (x < 0 || y < 0 || x >= m || y >= n) return;
        if (grid[x][y] == 0) 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);
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值