Source: Number of Enclaves - LeetCode
题解
踩过的坑:py的and是短路与,前面为F后面就不会执行,所以先把他们赋值,保证DFS运行
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m=len(grid);n=len(grid[0])
def dfs(x,y)->(int,bool):
if not (0<=x<m and 0<=y<n):return(0,False)
if grid[x][y]==1:
grid[x][y] = -1
_d=dfs(x-1,y)
_u=dfs(x+1,y)
_l=dfs(x,y-1)
_r=dfs(x,y+1)
return (_d[0] + _u[0] + _l[0] + _r[0] +1,
_d[1] and _u[1] and _l[1] and _r[1])
return (0,True)
_sum=0
for i in range(m):
for j in range(n):
if grid[i][j]==1:
c,b=dfs(i,j)
if b:_sum+=c
return _sum