Talentd
FleetCode
Make and follow sheets.Sign in

Find All Groups of Farmland solution and explanation

MediumArrayBreadth-First SearchDepth-First SearchMatrix6 min read75.6% acceptanceUpdated 9 Apr 2026
Find All Groups of Farmland | DFS | BFS | Brute Force | Leetcode 1992 | codestorywithMIKcodestorywithMIK · 32:39 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Find All Groups of Farmland | DFS | BFS | Brute Force | Leetcode 1992 | codestorywithMIKcodestorywithMIK · 32:39 · 6K views
  2. 1992. Find All Groups of Farmland | No BFS or DFS | GreedyAryan Mittal · 17:04 · 4K views
  3. LeetCode 1992. Find All Groups of Farmland | 🏆 Biweekly Contest 60 | ExplainedCherry Coding [IIT-G] · 16:13 · 3K views
  4. 1992. Find All Groups of Farmland (Leetcode Medium)Programming Live with Larry · 9:33 · 1K views
  5. Daily Leetcode #1481: Apr 20, 2024 - 1992. Find All Groups of FarmlandProgramming Live with Larry · 10:24 · 801 views
  6. Find All Groups of Farmland Leetcode 1992 || Biweekly Contest || Coding Culture5 Minutes Code · 9:56 · 726 views
  7. LeetCode 1992 - Find All Groups of Farmland: A Microsoft JourneyThe Lofi Dev · 10:31 · 679 views
  8. Leetcode 1992 : Find All Groups of FarmlandLearn Together · 25:26 · 655 views
  9. LeetCode 1992 - Find All Groups of Farmland - JavaAlpha-Code · 15:28 · 275 views
  10. Find All Groups of Farmland (LeetCode 1992)CodeWithARB · 16:29 · 181 views

The 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.

Example 1:

Input: land = [[1,0,0],[0,1,1],[0,1,1]]
Output: [[0,0,0,0],[1,1,2,2]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].
The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].

Example 2:

Input: land = [[1,1],[1,1]]
Output: [[0,0,1,1]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].

Example 3:

Input: land = [[0]]
Output: []
Explanation:
There are no groups of farmland.

Constraints:

  • m == land.length
  • n == land[i].length
  • 1 <= m, n <= 300
  • land consists of only 0's and 1's.
  • Groups of farmland are rectangular in shape.

Approach overview

Problem Overview: You are given a binary matrix where 1 represents farmland and 0 represents forest. Each farmland group forms a rectangular region of connected 1s. The task is to identify every group and return the coordinates of its top-left and bottom-right corners.

Approach 1: Breadth-First Search (BFS) to Identify Farmland Groups (Time: O(m*n), Space: O(m*n))

Scan the grid cell by cell. When you encounter an unvisited farmland cell (1), start a BFS from that position to explore the entire connected component. Use a queue and expand in four directions (up, down, left, right). While traversing, track the minimum and maximum row/column indices visited. These boundaries define the rectangle for that farmland group. Mark cells as visited to avoid processing them again.

This works because each farmland region is a connected block in the grid. BFS guarantees that all adjacent farmland cells are explored in one traversal. The algorithm touches every cell at most once, giving O(m*n) time complexity and O(m*n) space in the worst case for the visited structure and queue. This technique is a classic application of Breadth-First Search on a matrix grid.

Approach 2: Union-Find to Detect Connected Components (Time: O(m*n α(m*n)), Space: O(m*n))

Another option treats each farmland cell as a node in a disjoint-set structure. Iterate through the grid and union adjacent farmland cells (typically right and down neighbors to avoid duplicates). After building the sets, each root represents one connected farmland component. For every component, compute the bounding rectangle by tracking the minimum and maximum row and column indices among all cells belonging to that root.

The Union-Find data structure performs near-constant-time merges and finds due to path compression and union by rank. The total complexity becomes O(m*n α(m*n)), where α is the inverse Ackermann function. This approach is useful if you already use array-based disjoint sets or when solving multiple connectivity queries on the same grid.

Recommended for interviews: The BFS/DFS grid traversal is the approach most interviewers expect. It is simple, linear in time, and directly models the problem as a connected-component search. Implementing BFS or Depth-First Search shows strong understanding of graph traversal on matrices. Union-Find works as well but adds extra implementation overhead unless the problem explicitly requires dynamic connectivity.

Approach 1: Approach 1: Breadth-First Search (BFS) to Identify Farmland Groups

This approach uses a Breadth-First Search (BFS) algorithm to explore each group of farmland on the matrix.

Starting from a farmland cell (1), the BFS can be used to explore all connected cells that belong to the same group, thereby finding the bottom-right corner of that group. Use a queue to facilitate the exploration of individual farmlands.

Mark cells as visited as you explore them to ensure each cell is processed only once.

from collections import deque

def findFarmland(land):
    m, n = len(land), len(land[0])
    visited = [[False] * n for _ in range(m)]
    results = []

    for i in range(m):
        for j in range(n):
            if land[i][j] == 1 and not visited[i][j]:
                queue = deque([(i, j)])
                visited[i][j] = True
                max_row, max_col = i, j

                while queue:
                    row, col = queue.popleft()
                    max_row, max_col = max(max_row, row), max(max_col, col)

                    for drow, dcol in [(0, 1), (1, 0)]:
                        nrow, ncol = row + drow, col + dcol
                        if nrow < m and ncol < n and land[nrow][ncol] == 1 and not visited[nrow][ncol]:
                            visited[nrow][ncol] = True
                            queue.append((nrow, ncol))

                results.append([i, j, max_row, max_col])

    return results
import java.util.*;

class Solution {
    public List<int[]> findFarmland(int[][] land) {
        int m = land.length;
        int n = land[0].length;
        boolean[][] visited = new boolean[m][n];
        List<int[]> results = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1 && !visited[i][j]) {
                    int maxRow = i, maxCol = j;
                    Queue<int[]> queue = new LinkedList<>();
                    queue.offer(new int[]{i, j});
                    visited[i][j] = true;

                    while (!queue.isEmpty()) {
                        int[] coord = queue.poll();
                        int row = coord[0], col = coord[1];
                        maxRow = Math.max(maxRow, row);
                        maxCol = Math.max(maxCol, col);

                        int[][] directions = {{0, 1}, {1, 0}};
                        for (int[] dir : directions) {
                            int newRow = row + dir[0], newCol = col + dir[1];
                            if (newRow < m && newCol < n && land[newRow][newCol] == 1 && !visited[newRow][newCol]) {
                                visited[newRow][newCol] = true;
                                queue.offer(new int[]{newRow, newCol});
                            }
                        }
                    }
                    results.add(new int[]{i, j, maxRow, maxCol});
                }
            }
        }
        return results;
    }
}
#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    vector<vector<int>> findFarmland(vector<vector<int>>& land) {
        int m = land.size();
        int n = land[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        vector<vector<int>> results;
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (land[i][j] == 1 && !visited[i][j]) {
                    int minRow = i, minCol = j, maxRow = i, maxCol = j;
                    queue<pair<int, int>> que;
                    que.push({i, j});
                    visited[i][j] = true;

                    while (!que.empty()) {
                        auto [r, c] = que.front();
                        que.pop();
                        maxRow = max(maxRow, r);
                        maxCol = max(maxCol, c);

                        vector<pair<int, int>> directions = {{0, 1}, {1, 0}};
                        for (auto &[dr, dc] : directions) {
                            int newRow = r + dr, newCol = c + dc;
                            if (newRow < m && newCol < n && land[newRow][newCol] == 1 && !visited[newRow][newCol]) {
                                visited[newRow][newCol] = true;
                                que.push({newRow, newCol});
                            }
                        }
                    }
                    results.push_back({minRow, minCol, maxRow, maxCol});
                }
            }
        }

        return results;
    }
};
var findFarmland = function(land) {
    const m = land.length;
    const n = land[0].length;
    const visited = Array.from({ length: m }, () => Array(n).fill(false));
    const results = [];

    function bfs(row, col) {
        const queue = [[row, col]];
        let maxRow = row, maxCol = col;
        visited[row][col] = true;

        while (queue.length) {
            const [r, c] = queue.shift();
            maxRow = Math.max(maxRow, r);
            maxCol = Math.max(maxCol, c);

            const directions = [[0, 1], [1, 0]];
            for (const [dr, dc] of directions) {
                const newRow = r + dr, newCol = c + dc;
                if (newRow < m && newCol < n && land[newRow][newCol] === 1 && !visited[newRow][newCol]) {
                    visited[newRow][newCol] = true;
                    queue.push([newRow, newCol]);
                }
            }
        }
        results.push([row, col, maxRow, maxCol]);
    }

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (land[i][j] === 1 && !visited[i][j]) {
                bfs(i, j);
            }
        }
    }

    return results;
};
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

void bfs(int** land, bool** visited, int m, int n, int start_row, int start_col, int* end_row, int* end_col) {
    int directions[2][2] = {{0, 1}, {1, 0}};
    int queue[m * n][2];
    int front = 0, back = 0;
    queue[back][0] = start_row;
    queue[back][1] = start_col;
    back++;
    visited[start_row][start_col] = true;
    *end_row = start_row;
    *end_col = start_col;

    while (front < back) {
        int row = queue[front][0];
        int col = queue[front][1];
        front++;
        *end_row = row;
        *end_col = col;

        for (int i = 0; i < 2; i++) {
            int new_row = row + directions[i][0];
            int new_col = col + directions[i][1];
            if (new_row < m && new_col < n && !visited[new_row][new_col] && land[new_row][new_col] == 1) {
                visited[new_row][new_col] = true;
                queue[back][0] = new_row;
                queue[back][1] = new_col;
                back++;
            }
        }
    }
}

int** findFarmland(int** land, int m, int n, int* returnSize, int** returnColumnSizes) {
    bool** visited = (bool**)malloc(m * sizeof(bool*));
    for (int i = 0; i < m; i++) {
        visited[i] = (bool*)calloc(n, sizeof(bool));
    }
    
    int** results = (int**)malloc(m * n * sizeof(int*));
    *returnColumnSizes = (int*)malloc(m * n * sizeof(int));
    int count = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (land[i][j] == 1 && !visited[i][j]) {
                int end_row, end_col;
                bfs(land, visited, m, n, i, j, &end_row, &end_col);

                results[count] = (int*)malloc(4 * sizeof(int));
                results[count][0] = i;
                results[count][1] = j;
                results[count][2] = end_row;
                results[count][3] = end_col;
                (*returnColumnSizes)[count] = 4;
                count++;
            }
        }
    }

    *returnSize = count;
    for (int i = 0; i < m; i++) {
        free(visited[i]);
    }
    free(visited);
    return results;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int[][] FindFarmland(int[][] land) {
        int m = land.Length;
        int n = land[0].Length;
        bool[,] visited = new bool[m, n];
        var results = new List<int[]>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1 && !visited[i, j]) {
                    int maxRow = i, maxCol = j;
                    var queue = new Queue<(int, int)>();
                    queue.Enqueue((i, j));
                    visited[i, j] = true;

                    while (queue.Count > 0) {
                        var (row, col) = queue.Dequeue();
                        maxRow = Math.Max(maxRow, row);
                        maxCol = Math.Max(maxCol, col);

                        int[,] directions = { {0, 1}, {1, 0} };
                        for (int d = 0; d < directions.GetLength(0); d++) {
                            int newRow = row + directions[d, 0], newCol = col + directions[d, 1];
                            if (newRow < m && newCol < n && land[newRow][newCol] == 1 && !visited[newRow, newCol]) {
                                visited[newRow, newCol] = true;
                                queue.Enqueue((newRow, newCol));
                            }
                        }
                    }
                    results.Add(new int[] { i, j, maxRow, maxCol });
                }
            }
        }
        return results.ToArray();
    }
}

Python solution makes use of a deque for the BFS. Each expansion checks two directions to find the maximum row and column for the farm group.

Complexity

Time Complexity: O(m * n), every cell is explored once.

Space Complexity: O(m * n), for visited tracking and queue.

Try this approach in the editor

Approach 2: Approach 2: Union-Find to Detect Connected Components

This approach implements a Union-Find (also called Disjoint Set Union) data structure to efficiently group farmland cells together. After processing all connections, each cell will belong to a group denoted by its root, and by traversing all cells, we can identify the top-left and bottom-right corners of each group.

def findFarmland(land):
    m, n = len(land), len(land[0])
    parent = [i for i in range(m * n)]
    rank = [0] * (m * n)

    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]

    def union(x, y):
        rootX = find(x)
        rootY = find(y)
        if rootX != rootY:
            if rank[rootX] > rank[rootY]:
                parent[rootY] = rootX
            elif rank[rootX] < rank[rootY]:
                parent[rootX] = rootY
            else:
                parent[rootY] = rootX
                rank[rootX] += 1

    for i in range(m):
        for j in range(n):
            if land[i][j] == 1:
                index = i * n + j
                if i > 0 and land[i-1][j] == 1:
                    union(index, (i-1) * n + j)
                if j > 0 and land[i][j-1] == 1:
                    union(index, i * n + (j-1))

    bounds = {}
    for i in range(m):
        for j in range(n):
            if land[i][j] == 1:
                root = find(i * n + j)
                if root not in bounds:
                    bounds[root] = [i, j, i, j]
                else:
                    bounds[root][0] = min(bounds[root][0], i)
                    bounds[root][1] = min(bounds[root][1], j)
                    bounds[root][2] = max(bounds[root][2], i)
                    bounds[root][3] = max(bounds[root][3], j)

    return list(bounds.values())
import java.util.*;

class Solution {
    int[] parent, rank;

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    
    void unionSets(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX;
            } else if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++;
            }
        }
    }

    public List<int[]> findFarmland(int[][] land) {
        int m = land.length, n = land[0].length;
        parent = new int[m * n];
        rank = new int[m * n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1) {
                    int index = i * n + j;
                    parent[index] = index;
                    if (i > 0 && land[i-1][j] == 1) {
                        unionSets(index, (i-1) * n + j);
                    }
                    if (j > 0 && land[i][j-1] == 1) {
                        unionSets(index, i * n + (j-1));
                    }
                }
            }
        }

        Map<Integer, int[]> bounds = new HashMap<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1) {
                    int root = find(i * n + j);
                    int[] b = bounds.getOrDefault(root, new int[]{i, j, i, j});
                    b[0] = Math.min(b[0], i);
                    b[1] = Math.min(b[1], j);
                    b[2] = Math.max(b[2], i);
                    b[3] = Math.max(b[3], j);
                    bounds.put(root, b);
                }
            }
        }

        return new ArrayList<>(bounds.values());
    }
}
#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:
    vector<int> parent, rank;

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }

    void unionSets(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX;
            } else if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++;
            }
        }
    }

    vector<vector<int>> findFarmland(vector<vector<int>>& land) {
        int m = land.size();
        int n = land[0].size();
        parent.resize(m * n);
        rank.resize(m * n, 0);

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (land[i][j] == 1) {
                    int index = i * n + j;
                    parent[index] = index;
                    if (i > 0 && land[i-1][j] == 1) {
                        unionSets(index, (i-1) * n + j);
                    }
                    if (j > 0 && land[i][j-1] == 1) {
                        unionSets(index, i * n + (j-1));
                    }
                }
            }
        }

        unordered_map<int, vector<int>> bounds;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (land[i][j] == 1) {
                    int root = find(i * n + j);
                    if (!bounds.count(root)) {
                        bounds[root] = {i, j, i, j};
                    } else {
                        bounds[root][0] = min(bounds[root][0], i);
                        bounds[root][1] = min(bounds[root][1], j);
                        bounds[root][2] = max(bounds[root][2], i);
                        bounds[root][3] = max(bounds[root][3], j);
                    }
                }
            }
        }

        vector<vector<int>> results;
        for (auto& bound : bounds) {
            results.push_back(bound.second);
        }

        return results;
    }
};
function findFarmland(land) {
    const m = land.length;
    const n = land[0].length;
    const parent = Array.from({ length: m * n }, (_, i) => i);
    const rank = Array(m * n).fill(0);

    const find = (x) => {
        if (parent[x] !== x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    };

    const union = (x, y) => {
        const rootX = find(x);
        const rootY = find(y);
        if (rootX !== rootY) {
            if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX;
            } else if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++;
            }
        }
    };

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (land[i][j] === 1) {
                const index = i * n + j;
                if (i > 0 && land[i - 1][j] === 1) union(index, (i - 1) * n + j);
                if (j > 0 && land[i][j - 1] === 1) union(index, i * n + (j - 1));
            }
        }
    }

    const bounds = {};
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (land[i][j] === 1) {
                const root = find(i * n + j);
                if (!(root in bounds)) {
                    bounds[root] = [i, j, i, j];
                } else {
                    bounds[root][0] = Math.min(bounds[root][0], i);
                    bounds[root][1] = Math.min(bounds[root][1], j);
                    bounds[root][2] = Math.max(bounds[root][2], i);
                    bounds[root][3] = Math.max(bounds[root][3], j);
                }
            }
        }
    }

    return Object.values(bounds);
}
#include <stdio.h>
#include <stdlib.h>

int find(int x, int* parent) {
    if (parent[x] != x) {
        parent[x] = find(parent[x], parent);
    }
    return parent[x];
}

void unionSets(int x, int y, int* parent, int* rank) {
    int rootX = find(x, parent);
    int rootY = find(y, parent);
    if (rootX != rootY) {
        if (rank[rootX] > rank[rootY]) {
            parent[rootY] = rootX;
        } else if (rank[rootX] < rank[rootY]) {
            parent[rootX] = rootY;
        } else {
            parent[rootY] = rootX;
            rank[rootX]++;
        }
    }
}

int** findFarmland(int** land, int m, int n, int* returnSize, int** returnColumnSizes) {
    int* parent = malloc(m * n * sizeof(int));
    int* rank = calloc(m * n, sizeof(int));

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (land[i][j] == 1) {
                int index = i * n + j;
                parent[index] = index;
                if (i > 0 && land[i-1][j] == 1) {
                    unionSets(index, (i-1) * n + j, parent, rank);
                }
                if (j > 0 && land[i][j-1] == 1) {
                    unionSets(index, i * n + (j-1), parent, rank);
                }
            }
        }
    }

    int** bounds = malloc(m * n * sizeof(int*));
    for (int i = 0; i < m * n; i++) {
        bounds[i] = malloc(4 * sizeof(int));
        bounds[i][0] = m;
        bounds[i][1] = n;
        bounds[i][2] = 0;
        bounds[i][3] = 0;
    }

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (land[i][j] == 1) {
                int root = find(i * n + j, parent);
                if (i < bounds[root][0]) bounds[root][0] = i;
                if (j < bounds[root][1]) bounds[root][1] = j;
                if (i > bounds[root][2]) bounds[root][2] = i;
                if (j > bounds[root][3]) bounds[root][3] = j;
            }
        }
    }

    int** results = malloc(m * n * sizeof(int*));
    *returnColumnSizes = malloc(m * n * sizeof(int));
    int count = 0;
    for (int i = 0; i < m * n; i++) {
        if (bounds[i][0] <= bounds[i][2] && bounds[i][1] <= bounds[i][3]) {
            results[count] = malloc(4 * sizeof(int));
            results[count][0] = bounds[i][0];
            results[count][1] = bounds[i][1];
            results[count][2] = bounds[i][2];
            results[count][3] = bounds[i][3];
            (*returnColumnSizes)[count] = 4;
            count++;
        }
        free(bounds[i]);
    }

    *returnSize = count;
    free(bounds);
    free(parent);
    free(rank);
    return results;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int[][] FindFarmland(int[][] land) {
        int m = land.Length, n = land[0].Length;
        int[] parent = new int[m * n];
        int[] rank = new int[m * n];

        for (int i = 0; i < m * n; i++) {
            parent[i] = i;
        }

        int Find(int x) {
            if (parent[x] != x) {
                parent[x] = Find(parent[x]);
            }
            return parent[x];
        }

        void Union(int x, int y) {
            int rootX = Find(x);
            int rootY = Find(y);
            if (rootX != rootY) {
                if (rank[rootX] > rank[rootY]) {
                    parent[rootY] = rootX;
                } else if (rank[rootX] < rank[rootY]) {
                    parent[rootX] = rootY;
                } else {
                    parent[rootY] = rootX;
                    rank[rootX]++;
                }
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1) {
                    int index = i * n + j;
                    if (i > 0 && land[i-1][j] == 1) {
                        Union(index, (i-1) * n + j);
                    }
                    if (j > 0 && land[i][j-1] == 1) {
                        Union(index, i * n + (j-1));
                    }
                }
            }
        }

        var bounds = new Dictionary<int, int[]>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1) {
                    int root = Find(i * n + j);
                    if (!bounds.ContainsKey(root)) {
                        bounds[root] = new int[] { i, j, i, j };
                    } else {
                        bounds[root][0] = Math.Min(bounds[root][0], i);
                        bounds[root][1] = Math.Min(bounds[root][1], j);
                        bounds[root][2] = Math.Max(bounds[root][2], i);
                        bounds[root][3] = Math.Max(bounds[root][3], j);
                    }
                }
            }
        }

        var result = new List<int[]>(bounds.Values); 
        return result.ToArray();
    }
}

Python adopts the Union-Find algorithm: organizing cells into connected components and extracting the minimal bounding rectangle for each farmland group.

Complexity

Time Complexity: O(m * n * α(n)), where α(n) is a minor factor due to the inverse Ackermann function.

Space Complexity: O(m * n), from retained roots and operational rank values.

Try this approach in the editor

Approach 3: Default Approach

func findFarmland(land [][]int) [][]int {
	m, n := len(land), len(land[0])
	var ans [][]int
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if land[i][j] == 0 || (j > 0 && land[i][j-1] == 1) || (i > 0 && land[i-1][j] == 1) {
				continue
			}
			x, y := i, j
			for ; x+1 < m && land[x+1][j] == 1; x++ {
			}
			for ; y+1 < n && land[x][y+1] == 1; y++ {
			}
			ans = append(ans, []int{i, j, x, y})
		}
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Breadth-First Search (BFS) to Identify Farmland Groups

Time Complexity: O(m * n), every cell is explored once.

Space Complexity: O(m * n), for visited tracking and queue.

Approach 2: Union-Find to Detect Connected Components

Time Complexity: O(m * n * α(n)), where α(n) is a minor factor due to the inverse Ackermann function.

Space Complexity: O(m * n), from retained roots and operational rank values.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Breadth-First Search (BFS) Grid TraversalO(m*n)O(m*n)Best general solution for detecting connected farmland regions in a matrix.
Union-Find (Disjoint Set)O(m*n α(m*n))O(m*n)Useful when solving multiple connectivity problems or when components must be merged dynamically.

Frequently asked questions

Is Find All Groups of Farmland easy or hard?

The problem is rated Medium because it combines grid traversal with component boundary tracking. The BFS/DFS logic is straightforward, but correctly computing the rectangle coordinates and avoiding revisits requires careful implementation.

Find All Groups of Farmland Python/Java solution

Python and Java solutions typically implement BFS or DFS over the grid. Iterate through each cell, start a traversal when encountering a farmland cell (1), mark all reachable cells as visited, and record the bounding coordinates of the component before moving to the next group.

How to solve Find All Groups of Farmland in O(n)?

Treat the grid as a graph and perform BFS or DFS from every unvisited cell containing 1. Expand in four directions to mark all connected farmland cells. While traversing, track the minimum and maximum row and column indices to compute the top-left and bottom-right coordinates of the farmland rectangle.

What is the best approach for Find All Groups of Farmland?

Breadth-First Search (BFS) or Depth-First Search (DFS) on the grid is the most common solution. Start from every unvisited farmland cell and traverse the entire connected component while tracking its boundaries. This approach runs in O(m*n) time and directly identifies the rectangle representing each farmland group.

Is Find All Groups of Farmland asked at Google/Amazon/Meta?

Matrix traversal and connected-component problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. Variations often involve island detection, region counting, or grid-based BFS/DFS traversal.

What data structure is used in Find All Groups of Farmland?

The main data structures are a queue or recursion stack for BFS/DFS traversal and a visited matrix to avoid revisiting cells. An alternative approach uses a Union-Find (Disjoint Set) structure to group connected farmland cells into components.

What is the time complexity of Find All Groups of Farmland?

The optimal solution runs in O(m*n) time, where m and n are the grid dimensions. Each cell is visited at most once during BFS or DFS traversal. Space complexity is O(m*n) in the worst case due to the visited structure or recursion/queue storage.

Comments

Now write it yourselfClose this page and solve Find All Groups of Farmland in the editor, without looking.
Practise Find All Groups of Farmland