defdfs(row, col):if row <0or col <0or row >= m or col >= n ornot grid[row][col]:return0
grid[row][col]=0return dfs(row-1, col)+ \
dfs(row+1, col)+ \
dfs(row, col-1)+ \
dfs(row, col+1)+1ifnot grid:return0
m =len(grid)
n =len(grid[0])
ans =0for i inrange(m):for j inrange(n):if grid[i][j]:
ans =max(ans, dfs(i,j))return ans
defmaxDistance(grid: List[List[int]])->int:# 从1开始出发bfs,记录距离
m =len(grid)
n =len(grid[0])
start =[]# 存入所有起点1的位置for i inrange(m):for j inrange(n):if grid[i][j]:
start.append([i,j,0])# 特例ifnot start orlen(start)== m*n:return-1# 四个方向
x =[1,0,-1,0]
y =[0,1,0,-1]while start:
i, j, dis = start.pop(0)for k inrange(4):
row = i + x[k]
col = j + y[k]if row <0or col <0or row == m or col == n or grid[row][col]:continue
start.append([row,col,dis+1])
grid[row][col]=1#访问过的位置记录为1return dis #最后一个dis