关于岛屿的相似题目:
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
res = 0
m, n = len(grid), len(grid[0])
# 遍历grid,就是所有的封闭岛屿
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
res += self.dfs_matrix(grid, i, j)
return res
def dfs_matrix(self, grid, i, j):
m, n = len(grid), len(grid[0])
# 跳出递归条件
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0:
return 1
if grid[i][j] == 2:
return 0
grid[i][j] = 2
tmp = 0
tmp += self.dfs_matrix(grid, i - 1, j)
tmp += self.dfs_matrix(grid, i + 1, j)
tmp += self.dfs_matrix(grid, i, j - 1)
tmp += self.dfs_matrix(grid, i, j + 1)
return tmp