Problem Description
Given an m x n binary matrix land, where 0 represents forest land and 1 represents farmland, find all rectangular groups of farmland. Each group is a contiguous rectangular block of 1's that is not adjacent (four-directionally) to any farmland from a different group. Return the coordinates of the top left and bottom right corners for each group.
Key Insights
- The farmland groups are rectangular and non-adjacent; hence, once you find a farmland cell that is not visited, you can determine the entire rectangle.
- Use a double loop to iterate through each cell and when a 1 is encountered, determine the boundaries (bottom and right extents) of its group.
- Mark the entire rectangle as visited (or modify the matrix) so that overlapping is avoided.
- The problem can be solved in O(m*n) time since each cell is visited at most once.
Space and Time Complexity
Time Complexity: O(mn)
Space Complexity: O(1) extra space (if modifying the input is allowed) or O(mn) if a separate visited array is used.
Solution
The solution iterates over each cell in the matrix. When an unvisited farmland cell (value 1) is discovered, it is treated as the top left corner of a farmland group. Then, the algorithm expands in both the right and downward directions to determine the bottom right corner of that rectangle. After determining the bounds of the rectangle, all cells within are marked as visited by setting them to 0 (or using a visited marker) to prevent re-visiting. This guarantees that each farmland group is processed exactly once.