【题目】
【代码】dfs
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
C=0
visited=[[0 for i in range(len(grid[0]))] for i in range(len(grid))]
def dfs(x,y):
if x>=0 and x<len(grid) and y>=0 and y<len(grid[0]) and grid[x][y]==1 and visited[x][y]==0:
visited[x][y]=1
return [(x,y)]+dfs(x-1,y)+dfs(x+1,y)+dfs(x,y+1)+dfs(x,y-1)
return []
point=[]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1 and visited[i][j]==0:
temp=dfs(i,j)
if temp!=[]:
point=temp
for x,y in point:
for mx,my in [(x-1,y),(x+1,y),(x,y+1),(x,y-1)]:
if (0<=mx<len(grid) and 0<=my<len(grid[0]) and grid[mx][my]==0) or not(0<=mx<len(grid) and 0<=my<len(grid[0])):
C+=1
return C
【方法2】dfs
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
def dfs(grid,i,j):
if i<0 or i>=len(grid) or j<0 or j>=len(grid[0]):
return 1
if grid[i][j]==0:
return 1
if grid[i][j]==2:
return 0
grid[i][j]=2
return dfs(grid,i+1,j)+dfs(grid,i-1,j)+dfs(grid,i,j+1)+dfs(grid,i,j-1)
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
return dfs(grid,i,j)
return 0