A farmer has a rectangular grid of land with m rows and n columns where each cell can be either fertile (represented by 1) or barren (represented by 0). Your task is to count all possible pyramidal and inverse pyramidal plots that can be formed using only fertile cells.
A pyramidal plot has its apex at the top and expands downward in a diamond-like shape. For a pyramid with apex at position (r, c) and height h, it includes cells (i, j) where r ≤ i ≤ r + h - 1 and c - (i - r) ≤ j ≤ c + (i - r).
An inverse pyramidal plot has its apex at the bottom and expands upward. For an inverse pyramid with apex at (r, c) and height h, it includes cells (i, j) where r - h + 1 ≤ i ≤ r and c - (r - i) ≤ j ≤ c + (r - i).
Note: All pyramids must have height ≥ 2 (at least 4 cells total) and consist entirely of fertile land.
Input & Output
Visualization
Time & Space Complexity
For each of mn cells, we check up to min(m,n) heights, and each height check takes O(h) time
Only using constant extra space for variables
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 1000
- 1 ≤ m × n ≤ 105
- grid[i][j] is either 0 or 1