Find All Groups of Farmland — LeetCode 1992 Python Solution

MediumDepth-First SearchBreadth-First SearchArrayMatrix
Problem
#1992
Reading time
4 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview