class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
seen = [[False] * m for _ in range(n)]
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
level = 0
queue = []
count = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
queue.append((i, j))
seen[i][j] = True
count += 1
if count == 0 or count == n * m:
return -1
while queue:
num_level = len(queue)
for _ in range(num_level):
i, j = queue.pop(0)
for di, dj in directions:
ii, jj = i + di, j + dj
if 0 <= ii < n and 0 <= jj < m and seen[ii][jj] is False:
queue.append((ii, jj))
seen[ii][jj] = True
level += 1
return level - 1