Problems/1992. Find All Groups of Farmland

1992. Find All Groups of Farmland

MediumMatrixGraphDFSGreedy

You are given a 2D binary grid representing a map of land, where 1 represents farmland and 0 represents forested land. Farmland groups are rectangular, non-overlapping blocks of 1s.

Find the coordinates of all groups of farmland. For each group, you need to return its top-left coordinate (r1, c1) and its bottom-right coordinate (r2, c2) as [r1, c1, r2, c2].

Example 1
Input: grid = [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ]
Output: [[0,0,0,0], [1,1,2,2]]
There are two farmland groups: one isolated cell at (0,0) and a 2x2 rectangular group with corners at (1,1) and (2,2).
Example 2
Input: grid = [ [1, 1], [1, 1] ]
Output: [[0, 0, 1, 1]]
There is one large farm spanning from the top-left (0,0) to the bottom-right (1,1).
Example 3
Input: grid = [ [0] ]
Output: []
No farmland exists in the grid, so the result is empty.
Visualizer

Visualizer will appear here