#1992

Find All Groups of Farmland

Medium
ArrayDepth-First SearchBreadth-First SearchMatrixDepth-First Search (DFS)Breadth-First Search (BFS)Matrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the fact that each group of farmland is rectangular and non-adjacent. We can traverse the matrix and directly calculate the boundaries of each rectangle without needing to mark cells as visited.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty result list to store the coordinates of groups.
  2. 2Step 2: Loop through each cell in the matrix. When a '1' is found, record its position as the top-left corner.
  3. 3Step 3: Use a nested loop to find the bottom-right corner by checking the extent of the rectangle.
  4. 4Step 4: Add the coordinates of the rectangle to the result list.
  5. 5Step 5: Skip the cells that are part of the current rectangle to avoid redundant checks.
solution.py20 lines
1# Full working Python code
2
3def findFarmland(land):
4    result = []
5    m, n = len(land), len(land[0])
6    for i in range(m):
7        for j in range(n):
8            if land[i][j] == 1:
9                r1, c1 = i, j
10                r2, c2 = i, j
11                while r2 + 1 < m and land[r2 + 1][j] == 1:
12                    r2 += 1
13                while c2 + 1 < n and land[i][c2 + 1] == 1:
14                    c2 += 1
15                result.append([r1, c1, r2, c2])
16                # Skip the cells that are part of the current rectangle
17                for x in range(r1, r2 + 1):
18                    for y in range(c1, c2 + 1):
19                        land[x][y] = 0  # Mark as visited
20    return result

Complexity note: The time complexity is O(n) because we only traverse each cell once. The space complexity is O(n) due to the result list storing the coordinates of the rectangles.

  • 1Each group of farmland is rectangular and non-adjacent, which simplifies the search for boundaries.
  • 2Marking cells as visited helps avoid counting the same group multiple times.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.