Count Fertile Pyramids in a Land - 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). All cells outside the grid are considered barren.

A pyramidal plot of land can be defined as a set of cells with the following criteria:

  • The number of cells in the set has to be greater than 1 and all cells must be fertile.
  • The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).

An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:

  • The number of cells in the set has to be greater than 1 and all cells must be fertile.
  • The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).

Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[0,1,1,0],[1,1,1,1],[0,1,1,0],[1,1,1,1]]
Output: 2
💡 Note: Regular pyramid: apex at (1,1) with height 2. Inverse pyramid: apex at (2,1) with height 2. Total = 2 pyramids.
Example 2 — Single Row
$ Input: grid = [[1,1,1]]
Output: 0
💡 Note: Only one row, so no pyramids with height ≥ 2 can be formed.
Example 3 — All Fertile
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 4
💡 Note: Multiple pyramids can be formed: regular pyramids from top row and inverse pyramids from bottom row.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 1000
  • 1 ≤ m * n ≤ 105
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Count Fertile Pyramids in a LandInput GridRegular PyramidInverse PyramidAlgorithm Steps:1. Scan each cell as apex2. Check pyramid validityResult: 2 pyramids found
Understanding the Visualization
1
Input Grid
Binary matrix with fertile (1) and barren (0) cells
2
Find Pyramids
Identify valid pyramid shapes (regular and inverse)
3
Count Total
Sum all pyramids with height ≥ 2
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently track maximum pyramid heights at each position, avoiding redundant validations
Asked in
Google 12 Facebook 8 Amazon 6
12.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen