[LeetCode] Find All Groups of Farmland

1992. Find All Groups of Farmland

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
int n,m;
vector<int> bfs(vector<vector<int>>& A, int sy, int sx) {
int ty = sy, tx = sx, by = sy, bx = sx;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
queue<pair<int, int>> q;
q.push({sy,sx});
A[sy][sx] = 0;
while(!q.empty()) {
auto [y,x] = q.front(); q.pop();
ty = min(y,ty);
tx = min(x,tx);
by = max(y,by);
bx = max(x,bx);
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx] == 1) {
A[ny][nx] = 0;
q.push({ny,nx});
}
}
}

return {ty,tx,by,bx};
}
public:
vector<vector<int>> findFarmland(vector<vector<int>>& land) {
n = land.size(), m = land[0].size();
vector<vector<int>> res;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(land[i][j] == 0) continue;
res.push_back(bfs(land, i,j));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/12/PS/LeetCode/find-all-groups-of-farmland/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.