class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid) # 获取列表长度和宽度
steps = -1 # 初始化距离为-1
queue = [(i, j) for i in range(n) for j in range(n) if grid[i][j] == 1] # 将陆地加入队列
if len(queue) == 0 or len(queue) == n ** 2: return steps # 全是陆地或者海洋返回-1
while len(queue) > 0:
for _ in range(len(queue)): # 遍历队列
x, y = queue.pop(0) # 第一个出队列
for xi, yj in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]: #查询四周是海洋的位置 将其加入队列
if xi >= 0 and xi < n and yj >= 0 and yj < n and grid[xi][yj] == 0:
queue.append((xi, yj))
grid[xi][yj] = -1 #将查找过的位置赋值-1
steps += 1 # 遍历完之后路径距离+1 再次遍历队列直到队列长度为0
return steps