问题描述:给定一个二维矩阵,0表示水,1表示陆地,一个岛屿是指相邻的上下左右的陆地面积,求最大的岛屿
a=[[1,1,1,0,0,0], [1,1,1,0,0,0], [1,0,0,0,1,1], [0,1,1,0,1,0], [0,1,1,0,0,0]] area = 0 def maxAreaOfIsland(a): #记录地图的行,列 row=len(a) col=len(a[0]) for i in range(row): for j in range(col): if a[i][j]==1: #存储当前岛屿的面积 cur=1 #深度优先遍历 dfs(i,j,cur,a) return area def dfs(i,j,cur,a): #定义全局变量 global area #将以已经遍历过的标记 a[i][j]=2 if i>0 and a[i-1][j]==1: cur=dfs(i-1,j,cur+1,a) if i<len(a)-1 and a[i+1][j]==1: cur = dfs(i+1,j,cur+1,a) if j>0 and a[i][j-1]==1: cur=dfs(i,j-1,cur+1,a) if j<len(a[0])-1 and a[i][j+1]==1: cur=dfs(i,j+1,cur+1,a) #更新最大面积 area=max(area,cur) return cur print(maxAreaOfIsland(a)) 输出:7
另一种写法:
a=[[1,1,1,0,0,0], [1,1,1,0,0,0], [1,0,0,0,1,1], [0,1,1,0,1,0], [0,1,1,0,0,0]] def maxAreaOfIsland(a): global cur area = 0 row=len(a) col=len(a[0]) for i in range(row): for j in range(col): cur=0 dfs(i,j,a) area=max(cur,area) return area def dfs(i,j,a): global cur if i<0 or i>len(a)-1 or j<0 or j>len(a[0])-1 or a[i][j]!=1: return cur+=1 a[i][j]=2 dfs(i-1,j,a) dfs(i+1,j,a) dfs(i,j-1,a) dfs(i,j+1,a) print(maxAreaOfIsland(a)) 输出:7