forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-fertile-pyramids-in-a-land.cpp
60 lines (55 loc) · 1.95 KB
/
count-fertile-pyramids-in-a-land.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Time: O(m * n)
// Space: O(n)
class Solution {
public:
int countPyramids(vector<vector<int>>& grid) {
return count(grid, false) + count(grid, true);
}
private:
int count(const vector<vector<int>>& grid, int reverse) {
auto get_grid = [&grid, &reverse](int i, int j) {
return reverse ? grid[size(grid) - 1 - i][j] : grid[i][j];
};
int result = 0;
vector<int> dp(size(grid[0]));
for (int i = 1; i < size(grid); ++i) {
vector<int> new_dp(size(grid[0]));
for (int j = 1; j + 1 < size(grid[0]); ++j) {
if (get_grid(i, j) == get_grid(i - 1, j - 1) &&
get_grid(i - 1, j - 1) == get_grid(i - 1, j) &&
get_grid(i - 1, j) == get_grid(i - 1, j + 1) &&
get_grid(i - 1, j + 1) == 1) {
new_dp[j] = min(dp[j - 1], dp[j + 1]) + 1;
}
}
dp = move(new_dp);
result += accumulate(cbegin(dp), cend(dp), 0);
}
return result;
}
};
// Time: O(m * n)
// Space: O(m * n)
class Solution2 {
public:
int countPyramids(vector<vector<int>>& grid) {
return count(grid) + count(vector<vector<int>>(rbegin(grid), rend(grid)));
}
private:
int count(const vector<vector<int>>& grid) {
int result = 0;
vector<vector<int>> dp(size(grid), vector<int>(size(grid[0])));
for (int i = 1; i < size(grid); ++i) {
for (int j = 1; j + 1 < size(grid[0]); ++j) {
if (grid[i][j] == grid[i - 1][j - 1] &&
grid[i - 1][j - 1] == grid[i - 1][j] &&
grid[i - 1][j] == grid[i - 1][j + 1] &&
grid[i - 1][j + 1] == 1) {
dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i - 1][j + 1]}) + 1;
}
}
result += accumulate(cbegin(dp[i]), cend(dp[i]), 0);
}
return result;
}
};