As Far from Land as Possible — LeetCode 1162 Python Solution
- Problem
- #1162
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
Example
- Input
- grid = [[1,0,1],[0,0,0],[1,0,1]]
- Output
- 2
- Explanation
- The cell (1, 1) is as far as possible from all the land with distance 2.
Python solution
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j])
ans = -1
if len(q) in (0, n * n):
return ans
dirs = (-1, 0, 1, 0, -1)
while q:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
grid[x][y] = 1
q.append((x, y))
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1162. As Far from Land as Possible is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1162. As Far from Land as Possible?
- LeetCode 1162. As Far from Land as Possible is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1162. As Far from Land as Possible?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1162. As Far from Land as Possible?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 1162. As Far from Land as Possible cover?
- LeetCode 1162. As Far from Land as Possible is tagged Breadth-First Search, Array, Dynamic Programming and Matrix on LeetCode.