2
def countPyramids(self, grid):3
# dp[i][j] represents the number of layers of the largest pyramid with (i, j) as the vertex.4
# Note that the 1-level pyramid is invalid in the problem, so it should be removed when summing.5
# Note that if grid[i][j] is 0, dp[i][j] will always be 0.6
# The dp recurrence formula is dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 17
m, n, dp, cnt = len(grid), len(grid[0]), copy.deepcopy(grid), 09
for i in range(m - 2, -1, -1):10
for j in range(1, n - 1):11
if dp[i][j] > 0 and dp[i + 1][j] > 0:12
dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 117
for j in range(1, n - 1):18
if dp[i][j] > 0 and dp[i - 1][j] > 0:19
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j + 1]) + 1