Find All Groups of Farmland - 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. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.

land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].

Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.

Input & Output

Example 1 — Two Separate Groups
$ Input: land = [[1,0,0],[0,1,1],[0,1,1]]
Output: [[0,0,0,0],[1,1,2,2]]
💡 Note: First group is single cell at (0,0). Second group forms 2×2 rectangle from (1,1) to (2,2).
Example 2 — Single Large Rectangle
$ Input: land = [[1,1],[1,1]]
Output: [[0,0,1,1]]
💡 Note: Entire 2×2 matrix is one farmland group with corners at (0,0) and (1,1).
Example 3 — No Farmland
$ Input: land = [[0,0],[0,0]]
Output: []
💡 Note: No farmland cells found, so return empty array.

Constraints

  • m == land.length
  • n == land[i].length
  • 1 ≤ m, n ≤ 300
  • land[i][j] is 0 or 1
  • Groups of farmland are rectangular in shape

Visualization

Tap to expand
Find All Groups of FarmlandInput Matrix100001100110PROCESSGroup DetectionG1G2RESULTOutput CoordinatesGroup 1: [0,0,0,0]Single cell at (0,0)Group 2: [1,1,2,2]Each farmland group forms a perfect rectangleOutput: [[0,0,0,0], [1,1,2,2]]
Understanding the Visualization
1
Input Matrix
Binary matrix with 1=farmland, 0=forest
2
Find Groups
Identify connected rectangular farmland regions
3
Output Coordinates
Return [top-left, bottom-right] for each group
Key Takeaway
🎯 Key Insight: Farmland groups are guaranteed rectangles, so we can find boundaries efficiently without full traversal
Asked in
Amazon 25 Google 20 Microsoft 15 Facebook 12
32.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen