-
Notifications
You must be signed in to change notification settings - Fork 2
/
pond_sizes_lcci.cpp
38 lines (34 loc) · 1.04 KB
/
pond_sizes_lcci.cpp
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
// 水域大小
// https://leetcode.cn/problems/pond-sizes-lcci
// INLINE ../../images/search/pond_sizes_lcci.jpeg
#include <headers.hpp>
class Solution {
public:
vector<int> pondSizes(vector<vector<int>> &land) {
int m = land.size(), n = land[0].size();
// List of directions to traverse (up, down, left, right, diagonals)
vector<pair<int, int>> directions{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},
{0, 1}, {1, -1}, {1, 0}, {1, 1}};
function<int(int, int)> dfs = [&](int x, int y) -> int {
if (x < 0 || x >= m || y < 0 || y >= n || land[x][y] != 0) {
return 0;
}
land[x][y] = -1; // Mark as visited
int res = 1;
for (const auto &dir : directions) {
res += dfs(x + dir.first, y + dir.second);
}
return res;
};
vector<int> res;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (land[i][j] == 0) {
res.push_back(dfs(i, j));
}
}
}
sort(res.begin(), res.end());
return res;
}
};