The Count Fertile Pyramids in a Land coding problem involves a 2D grid representing land where 1 is fertile and 0 is barren. You need to count all "fertile pyramids" and "inverse fertile pyramids." A pyramid of height h has a base of 2h-1 fertile cells and tapers up to a single fertile cell at the apex.
Google asks the Matrix interview pattern for this problem to test your ability to use Dynamic Programming in 2D grids. It’s a "Hard" difficulty problem because counting every possible pyramid manually is too slow. It evaluates whether you can define a DP state where dp[r][c] represents the maximum height of a pyramid centered at that cell.
The problem uses 2D Dynamic Programming.
dp[r][c] as the height of the largest pyramid whose apex is at (r, c).dp[r][c] = 1 + min(dp[r+1][c-1], dp[r+1][c], dp[r+1][c+1]).dp[r][c] = h is h - 1 (since a height-1 cell is just a cell, not a pyramid).(dp[r][c] - 1) for all cells in both passes.Grid:
0 1 0
1 1 1
(0, 1) has 1, 1, 1 below it.dp[0][1] = 1 + min(dp[1][0], dp[1][1], dp[1][2]) = 1 + 1 = 2.2 - 1 = 1.
Result: 1.h needs a specific horizontal spread at each level.This problem is very similar to "Count Square Submatrices." If you can solve the square problem, you can solve the pyramid problem by adjusting the min() condition to look at three neighbors instead of two.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check if There Is a Valid Parentheses String Path | Hard | Solve | |
| Paths in Matrix Whose Sum Is Divisible by K | Hard | Solve | |
| Maximum Vacation Days | Hard | Solve | |
| Minimum Falling Path Sum II | Hard | Solve | |
| Cherry Pickup II | Hard | Solve |