------
## 最终结论
```python
from collections import deque

def maxDistance(grid):
    n = len(grid)
    queue = deque()
    
    # Directions for moving up, down, left, right
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    # Initialize the queue with all land cells
    for i in range(n):
        for j in range(n):
            if grid[i][j] == 1:
                queue.append((i, j))
    
    # Check for special cases: if there is no land or no water
    if not queue or len(queue) == n * n:
        return -1
    
    # Perform BFS from all land cells
    distance = -1  # Initialize distance to track maximum distance
    
    while queue:
        distance += 1  # Increase the distance for each layer of BFS
        for _ in range(len(queue)):
            x, y = queue.popleft()
            for dx, dy in directions:
                nx, ny = x + dx, y + dy
                if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
                    grid[nx][ny] = -1  # Mark this water cell as visited
                    queue.append((nx, ny))  # Add it to the queue for further exploration

    return distance
```