LeetCode 1020. Number of Enclaves 解题报告(python)

本文介绍了一种使用深度优先搜索(DFS)算法解决LeetCode上编号为1020的“岛屿数量”问题的Python解决方案。问题描述了一个二维数组,其中1表示陆地,0表示海洋,目标是计算无法从边界到达的陆地数量。文章详细解释了如何通过DFS遍历边界上的陆地,并最终计算不可达陆地的总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1020. Number of Enclaves

  1. Number of Enclaves python solution

题目描述

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

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

在这里插入图片描述

解析

1代表小岛,0代表海洋。题目要求我们从边界出发,遍历所有小岛,求得不能到达小岛的个数。

class Solution:
    def numEnclaves(self, A: List[List[int]]) -> int:
        m, n = len(A), len(A[0])
        def dfs(i, j):
            A[i][j] = 0
            for x, y in (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1):
                if 0 <= x < m and 0 <= y < n and A[x][y]:
                    dfs(x, y)

        for i in range(m):
            for j in range(n):
                if A[i][j] == 1 and (i == 0 or j == 0 or i == m - 1 or j == n - 1):
                    dfs(i, j)
        return sum(sum(row) for row in A)
        

Reference

https://leetcode.com/problems/number-of-enclaves/discuss/265534/Python-clean-DFS-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值