DFS解决岛屿问题(2)
1020. 飞地的数量
加条件的 岛屿统计问题 和之前一样 先腐蚀一边边缘 把陆地都腐蚀了 再统计陆地
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m , n = len(grid),len(grid[0])
res= 0
def dfs(x,y):
grid[x][y]=0
for i,j in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=i<m and 0<=j<n and grid[i][j]==1:
dfs(i,j)
for i in range(n):
if grid[0][i] ==1:
dfs(0,i)
if grid[m-1][i]==1:
dfs(m-1,i)
for i in range(m):
if grid[i][0] ==1:
dfs(i,0)
if grid[i][n-1]==1:
dfs(i,n-1)
for i in range(1,m-1):
for j in range(1,n-1):
if grid[i][j]==1:
res+=1
return res
1905. 统计子岛屿
同样的方法 先把地图二中陆地但是在一中是水域的土地 深度腐蚀,然后再统计
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
m,n = len(grid1),len(grid1[0])
res = 0
def dfs(x,y):
grid2[x][y]=0
for i,j in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=i<m and 0<=j<n and grid2[i][j]==1:
dfs(i,j)
for i in range(m):
for j in range(n):
if grid1[i][j]==0 and grid2[i][j]:
dfs(i,j)
for i in range(m):
for j in range(n):
if grid2[i][j]:
res+=1
dfs(i,j)
return res