力扣 1020. 飞地的数量

题目来源:https://leetcode-cn.com/problems/number-of-enclaves/

大致题意:
给一个矩阵网格,元素由 1 和 0 组成,其中 1 表示陆地, 0 表示水域,求出不在边缘的且周围只有水域的陆地个数

思路

可以使用多源最短路径来解题,出发点为边缘的所有陆地点,然后搜索内部的陆地点,最后未被搜索到的陆地就是所求数目

多源最短路径
  1. 遍历网格,统计内部的陆地个数 count,并将边缘的陆地作为起点放入队列中
  2. BFS 内部陆地,每寻找到一个,将之前统计的陆地个数 count 减 1
  3. BFS 结束后,此时的 count 即为所求

代码:

	public int numEnclaves(int[][] grid) {
        Queue<int[]> queue = new ArrayDeque<>();
        int[] direction = new int[]{1, 0, -1, 0, 1};
        int landCount = 0;
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 若为水域,直接跳过
                if (grid[i][j] == 0) {
                    continue;
                }
                // 若为边缘陆地,放入队列
                if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
                    queue.offer(new int[]{i, j});
                    // 已搜索的陆地置 0,防止重复搜索
                    grid[i][j] = 0;
                } else {
                    // 统计内部陆地数
                    landCount++;
                }
            }
        }
        // BFS
        while (!queue.isEmpty()) {
            int[] coordinate = queue.poll();
            int x = coordinate[0];
            int y = coordinate[1];
            for (int i = 0; i < 4; i++) {
                int newX = x + direction[i];
                int newY = y + direction[i + 1];
                if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] != 0) {
                    // 更新未搜索的陆地(即内部陆地)数目
                    landCount--;
                    queue.offer(new int[]{newX, newY});
                    // 已搜索的陆地置 0,防止重复搜索
                    grid[newX][newY] = 0;
                }
            }
        }
        return landCount;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三更鬼

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值