当前位置:网站首页>[leetcode daily clock in] 1020 Number of enclaves

[leetcode daily clock in] 1020 Number of enclaves

2022-07-06 22:11:00 yyhnet. cn

[]

class Solution:
    def numEnclaves(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        vis = [[False] * n for _ in range(m)]
        def dfs(r: int, c: int) -> None:
            if r < 0 or r >= m or c < 0 or c >= n or grid[r][c] == 0 or vis[r][c]:
                return
            vis[r][c] = True
            for x, y in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
                dfs(x, y)

        for i in range(m):
            dfs(i, 0)
            dfs(i, n - 1)
        for j in range(1, n - 1):
            dfs(0, j)
            dfs(m - 1, j)
        return sum(grid[i][j] and not vis[i][j] for i in range(1, m - 1) for j in range(1, n - 1))

1. adopt DFS Traversal can calculate whether the current point can go to the ground , If the current point is not outside the boundary and is land , And it is marked as True, And continue to traverse the surrounding points .
2. By judging the number of ground that cannot be walked out , That is, the current statistics is False Land parcel of , You can get the answer .

原网站

版权声明
本文为[yyhnet. cn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131102421236.html