def maxDistance(grid: List[List[int]]) -> int:
q, visited, n = deque(), set(), len(grid)
for y in range(n):
for x in range(n):
if grid[y][x] == 1:
# initialize all lands
q.append((y, x))
visited.add((y, x))
farthest = -1
while q:
turns = len(q) # exhaust all current position
while turns:
turns -= 1
y, x = q.popleft()
for ny, nx in ((y+1, x), (y-1, x), (y, x+1), (y, x-1)):
if not (0 <= ny < n) or not (0 <= nx < n):
continue
if (ny, nx) in visited or grid[ny][nx] != 0:
continue
# now (ny, nx) is reachable water
q.append((ny, nx))
visited.add((ny, nx))
farthest += 1
return farthest if farthest else -1