Find All Groups of Farmland - Problem
Find All Rectangular Groups of Farmland
You're given an
Key constraints:
• All farmland groups are rectangular in shape
• No two groups are adjacent (separated by forest or boundaries)
• Groups cannot be diagonal - only 4-directionally connected
Goal: Find the coordinates of the top-left and bottom-right corners of each rectangular farmland group. Return each group as
Example: If you find a farmland rectangle from
You're given an
m x n binary matrix representing land where 0 represents forested areas and 1 represents farmland. The farmland is organized into rectangular groups - each group forms a perfect rectangle of connected farmland.Key constraints:
• All farmland groups are rectangular in shape
• No two groups are adjacent (separated by forest or boundaries)
• Groups cannot be diagonal - only 4-directionally connected
Goal: Find the coordinates of the top-left and bottom-right corners of each rectangular farmland group. Return each group as
[r1, c1, r2, c2] where (r1, c1) is top-left and (r2, c2) is bottom-right.Example: If you find a farmland rectangle from
(1,1) to (3,4), return [1, 1, 3, 4]. Input & Output
example_1.py — Basic rectangular groups
$
Input:
land = [[1,0,0],[0,1,1],[0,1,1]]
›
Output:
[[0,0,0,0],[1,1,2,2]]
💡 Note:
The first group is a 1x1 rectangle at position (0,0). The second group is a 2x2 rectangle from (1,1) to (2,2). Both are separate rectangular farmland areas.
example_2.py — Single large rectangle
$
Input:
land = [[1,1],[1,1]]
›
Output:
[[0,0,1,1]]
💡 Note:
The entire 2x2 matrix forms one rectangular group of farmland, with top-left at (0,0) and bottom-right at (1,1).
example_3.py — No farmland (edge case)
$
Input:
land = [[0,0,0],[0,0,0]]
›
Output:
[]
💡 Note:
There is no farmland in the matrix (all cells are 0), so we return an empty array as there are no groups to identify.
Constraints
- m == land.length
- n == land[i].length
- 1 ≤ m, n ≤ 300
- land[i][j] is either 0 or 1
- All farmland groups are rectangular
- No two groups are adjacent
Visualization
Tap to expand
Understanding the Visualization
1
Aerial Survey Begins
Start systematic scan from top-left, moving row by row
2
Spot Farm Corner
Identify top-left corner: farmland with no farms above or left
3
Trace Eastern Boundary
Follow the farm's eastern edge to find rightmost extent
4
Trace Southern Boundary
Follow the farm's southern edge to find bottommost extent
5
Mark Territory
Record farm boundaries and mark as surveyed
6
Continue Survey
Move to next unsurveyed area and repeat process
Key Takeaway
🎯 Key Insight: By identifying top-left corners (farmland cells with no farmland above or to the left), we can efficiently trace each rectangular farm's boundaries without redundant exploration, achieving optimal O(m*n) time complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code