Sponsored
Sponsored
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.
Time Complexity: O(m * n), as each cell is visited at most once.
Space Complexity: O(m * n) in the worst case due to additional space used for storing visited cells and the queue.
1#include <vector>
2#include <queue>
3using namespace std;
4
5class Solution {
6public:
7 vector<vector<int>> findFarmland(vector<vector<int>>& land) {
8 int m = land.size();
9 int n = land[0].size();
10 vector<vector<bool>> visited(m, vector<bool>(n, false));
11 vector<vector<int>> results;
12
13 for (int i = 0; i < m; ++i) {
14 for (int j = 0; j < n; ++j) {
15 if (land[i][j] == 1 && !visited[i][j]) {
16 int minRow = i, minCol = j, maxRow = i, maxCol = j;
17 queue<pair<int, int>> que;
18 que.push({i, j});
19 visited[i][j] = true;
20
21 while (!que.empty()) {
22 auto [r, c] = que.front();
23 que.pop();
24 maxRow = max(maxRow, r);
25 maxCol = max(maxCol, c);
26
27 vector<pair<int, int>> directions = {{0, 1}, {1, 0}};
28 for (auto &[dr, dc] : directions) {
29 int newRow = r + dr, newCol = c + dc;
30 if (newRow < m && newCol < n && land[newRow][newCol] == 1 && !visited[newRow][newCol]) {
31 visited[newRow][newCol] = true;
32 que.push({newRow, newCol});
33 }
34 }
35 }
36 results.push_back({minRow, minCol, maxRow, maxCol});
37 }
38 }
39 }
40
41 return results;
42 }
43};
The BFS explores the '1's around unvisited cells to discover each farmland rectancle's boundaries, collecting the minimum and maximum boundary values for rows and columns.
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.
Time Complexity: O(m * n * α(n)), with α being the inverse Ackermann function, which grows very slowly, making this almost O(m * n).
Space Complexity: O(m * n) due to storage for parents and ranks of each cell.
The Union-Find method first connects all farmland cells through union operations to find connected components. Each component is evaluated to find the top-left and bottom-right coordinates.