-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode2088.cpp
58 lines (57 loc) · 1.7 KB
/
leetcode2088.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
// 左右前缀和算最大可行的宽度,上下dp求最大可行的高度
class Solution {
public:
int countPyramids(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> left(m, vector<int>(n, 0));
vector<vector<int>> right(m, vector<int>(n, 0));
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(j == 0)
left[i][j] = grid[i][j];
else
left[i][j] = (grid[i][j] == 1) ? left[i][j-1] + 1: 0;
}
}
for(int i = 0; i < m; i++)
{
for(int j = n - 1; j >= 0; j--)
{
if(j == n - 1)
right[i][j] = grid[i][j];
else
right[i][j] = (grid[i][j] == 1) ? right[i][j+1] + 1: 0;
left[i][j] = min(left[i][j], right[i][j]);
}
}
int result = 0;
auto dp = left;
for(int j = 0; j < n; j++)
{
for(int i = 0; i < m; i++)
{
if(i == 0)
dp[i][j] = min(dp[i][j], 1);
else
dp[i][j] = min(dp[i][j], dp[i-1][j] + 1);
result += max(dp[i][j] - 1, 0);
}
}
dp = left;
for(int j = 0; j < n; j++)
{
for(int i = m - 1; i >= 0; i--)
{
if(i == m - 1)
dp[i][j] = min(dp[i][j], 1);
else
dp[i][j] = min(dp[i][j], dp[i+1][j] + 1);
result += max(dp[i][j] - 1, 0);
}
}
return result;
}
};