Leetcode 1992: Find All Groups of Farmland

grid47
grid47
Exploring patterns and algorithms
Apr 21, 2024 7 min read

You are given an m x n binary matrix representing a piece of land, where ‘1’ denotes farmland and ‘0’ denotes forest. Your task is to identify the coordinates of each rectangular group of contiguous farmland (1’s), where each group of farmland is isolated and not adjacent to another group. Return a list of 4-length arrays, where each array represents the top-left and bottom-right coordinates of a rectangular farmland group.
Problem
Approach
Steps
Complexity
Input: The input consists of an m x n binary matrix 'land'. Each element in the matrix is either 0 (forest) or 1 (farmland).
Example: land = [[1, 0, 0], [0, 1, 1], [0, 1, 1]]
Constraints:
• 1 <= m, n <= 300
• land[i][j] is either 0 or 1.
Output: The output should be a 2D list of arrays, where each array consists of four integers representing the coordinates of the top-left and bottom-right corners of a group of farmland. If no groups of farmland exist, return an empty list.
Example: Output: [[0, 0, 0, 0], [1, 1, 2, 2]]
Constraints:
• The output should be in any order.
Goal: The goal is to find all the rectangular groups of farmland, starting from each cell that contains a '1', and determine the boundaries of the rectangle.
Steps:
• Iterate through the matrix and for each '1', explore the connected '1's to determine the rectangular area it covers.
• Mark the visited cells as '0' to avoid counting the same farmland group again.
• Store the top-left and bottom-right coordinates of each farmland group.
Goal: Ensure the algorithm efficiently handles large matrices up to the maximum size of 300x300.
Steps:
• Each group of farmland is rectangular.
• No two groups of farmland are adjacent.
Assumptions:
• The input matrix contains only '0's and '1's, representing forest and farmland, respectively.
Input: Input: land = [[1, 0, 0], [0, 1, 1], [0, 1, 1]]
Explanation: The first group of farmland starts at (0, 0) and ends at (0, 0). The second group of farmland starts at (1, 1) and ends at (2, 2).

Input: Input: land = [[1, 1], [1, 1]]
Explanation: The only group of farmland starts at (0, 0) and ends at (1, 1).

Input: Input: land = [[0]]
Explanation: There are no groups of farmland, so the output is an empty list.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus