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

被折叠的 条评论
为什么被折叠?



