你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
输出: [1,2,4]
提示:
0 < len(land) <= 1000
0 < len(land[i]) <= 1000
一、DFS
数过的0变为1
class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
row = len(land)
col = len(land[0])
def dfs(i,j):
if not(0<=i<row and 0<=j<col and land[i][j] == 0):
return 0
land[i][j] = 1
return 1 + dfs(i-1,j)+dfs(i-1,j-1)+dfs(i-1,j+1)+dfs(i,j-1)+dfs(i,j+1)+dfs(i+1,j-1)+dfs(i+1,j)+dfs(i+1,j+1)
res = []
for i in range(row):
for j in rnage(col):
if land[i][j] == 0:
res.append(dfs(i,j))
res.sort()
return res