Find All Groups of Farmland — LeetCode 1992 Python Solution
- Problem
- #1992
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland.
Example
- Input
- land = [[1,0,0],[0,1,1],[0,1,1]]
- Output
- [[0,0,0,0],[1,1,2,2]]
- Explanation
- The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].
Python solution
class Solution:
def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
m, n = len(land), len(land[0])
ans = []
for i in range(m):
for j in range(n):
if (
land[i][j] == 0
or (j > 0 and land[i][j - 1] == 1)
or (i > 0 and land[i - 1][j] == 1)
):
continue
x, y = i, j
while x + 1 < m and land[x + 1][j] == 1:
x += 1
while y + 1 < n and land[x][y + 1] == 1:
y += 1
ans.append([i, j, x, y])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1992. Find All Groups of Farmland 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 1992. Find All Groups of Farmland?
- LeetCode 1992. Find All Groups of Farmland is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1992. Find All Groups of Farmland?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 1992. Find All Groups of Farmland?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 1992. Find All Groups of Farmland cover?
- LeetCode 1992. Find All Groups of Farmland is tagged Depth-First Search, Breadth-First Search, Array and Matrix on LeetCode.