Find All Groups of Farmland LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> nbrs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
4
pair<int, int> dfs(vector<vector<int>> &land, int i, int j, vector<vector<bool>> &visited) {
5
visited[i][j] = true;
6
pair<int, int> res = make_pair(i, j);
7
for (auto &nbr : nbrs) {
8
int x = i + nbr[0];
9
int y = j + nbr[1];
10
if (x < 0 || y < 0 || x >= land.size() || y >= land[0].size() || visited[x][y] ||
11
land[x][y] != 1)
12
continue;
13
pair<int, int> ans = dfs(land, x, y, visited);
14
res.first = max(res.first, ans.first);
15
res.second = max(res.second, ans.second);
16
}
17
return res;
18
}
19
vector<vector<int>> findFarmland(vector<vector<int>> &land) {
20
int m = land.size();
21
int n = land[0].size();
22
vector<vector<bool>> visited(m, vector<bool>(n, false));
23
vector<vector<int>> ans;
24
for (int i = 0; i < m; i++) {
25
for (int j = 0; j < n; j++) {
26
if (!visited[i][j] && land[i][j] == 1) {
27
pair<int, int> p = dfs(land, i, j, visited);
28
vector<int> res;
29
res.push_back(i);
30
res.push_back(j);
31
res.push_back(p.first);
32
res.push_back(p.second);
33
ans.push_back(res);
34
cout << 1 << endl;
35
}
36
}
37
}
38
return ans;
39
}
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0