#1162

As Far from Land as Possible

Medium
ArrayDynamic ProgrammingBreadth-First SearchMatrixBreadth-First SearchMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

Instead of checking each water cell, we can use a Breadth-First Search (BFS) starting from all land cells simultaneously. This way, we can efficiently calculate the distance to the nearest land for all water cells in one pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue and add all land cells to it.
  2. 2Step 2: Perform BFS from all land cells, marking distances for each water cell as we go.
  3. 3Step 3: Track the maximum distance encountered during the BFS.
solution.py24 lines
1from collections import deque
2
3def maxDistance(grid):
4    n = len(grid)
5    queue = deque()
6    for i in range(n):
7        for j in range(n):
8            if grid[i][j] == 1:
9                queue.append((i, j))
10    if not queue or len(queue) == n * n:
11        return -1
12
13    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
14    max_dist = -1
15    while queue:
16        for _ in range(len(queue)):
17            x, y = queue.popleft()
18            for dx, dy in directions:
19                nx, ny = x + dx, y + dy
20                if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
21                    grid[nx][ny] = grid[x][y] + 1
22                    max_dist = max(max_dist, grid[nx][ny])
23                    queue.append((nx, ny))
24    return max_dist - 1

Complexity note: The time complexity is O(n²) due to visiting each cell once, while the space complexity is O(n) for the queue used in BFS.

  • 1Using BFS allows us to explore all paths simultaneously, which is more efficient than checking each water cell individually.
  • 2Manhattan distance is straightforward to calculate, but understanding how to optimize the search is key.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.