classSolution: defmaxDistance(self, grid: List[List[int]]) -> int: n = len(grid) steps = -1 queue = [(i, j) for i in range(n) for j in range(n) if grid[i][j] == 1] if len(queue) == 0or len(queue) == n ** 2: return steps 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 >= 0and xi < n and yj >= 0and yj < n and grid[xi][yj] == 0: queue.append((xi, yj)) grid[xi][yj] = -1 steps += 1
return steps
由于没有 early return,steps 其实会多算一次。 我们可以返回值减去 1,也可以 steps 初始化为-1。这里我选择是 steps 初始化为-1
defmaxDistance(self, grid: List[List[int]]) -> int: from collections import deque N = len(grid) steps = -1 q = deque([(i, j) for i in range(N) for j in range(N) if grid[i][j] == 1]) if len(q) == 0or len(q) == N ** 2: return steps move = [(-1, 0), (1, 0), (0, -1), (0, 1)] while len(q) > 0: for _ in range(len(q)): x, y = q.popleft() for dx, dy in move: nx, ny = x + dx, y + dy if0 <= nx < N and0 <= ny < N and grid[nx][ny] == 0: q.append((nx, ny)) grid[nx][ny] = -1 steps += 1