HardNo. 2088
Count Fertile Pyramids in a Land — LeetCode 2088 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Dynamic Programming, Matrix
- Reading time
- 4 min
- Source
- leetcode.com
The problem
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0).
Example
- Input
- grid = [[0,1,1,0],[1,1,1,1]]
- Output
- 2
- Explanation
- The 2 possible pyramidal plots are shown in blue and red respectively.
Python solution
class Solution:
def countPyramids(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i in range(m - 1, -1, -1):
for j in range(n):
if grid[i][j] == 0:
f[i][j] = -1
elif not (i == m - 1 or j == 0 or j == n - 1):
f[i][j] = min(f[i + 1][j - 1], f[i + 1][j], f[i + 1][j + 1]) + 1
ans += f[i][j]
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
f[i][j] = -1
elif i == 0 or j == 0 or j == n - 1:
f[i][j] = 0
else:
f[i][j] = min(f[i - 1][j - 1], f[i - 1][j], f[i - 1][j + 1]) + 1
ans += f[i][j]
return ansComplexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2088. Count Fertile Pyramids in a Land is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0063 | Unique Paths II | Medium |
| 0064 | Minimum Path Sum | Medium |
| 0085 | Maximal Rectangle | Hard |
| 0174 | Dungeon Game | Hard |
| 0221 | Maximal Square | Medium |
| 0329 | Longest Increasing Path in a Matrix | Hard |
Frequently asked questions
- How hard is LeetCode 2088. Count Fertile Pyramids in a Land?
LeetCode 2088. Count Fertile Pyramids in a Land is rated Hard on LeetCode.
- What topics does LeetCode 2088. Count Fertile Pyramids in a Land cover?
LeetCode 2088. Count Fertile Pyramids in a Land is tagged Array, Dynamic Programming and Matrix on LeetCode.