1129. Local Peak Cells
A map of an m x n region stores the height of every square in grid. A hiker calls a square a peak if its height is strictly greater than the height of every neighbouring square that shares an edge with it, meaning up to four neighbours: up, down, left and right.
Squares on the border simply have fewer neighbours, and the single square of a 1 x 1 map counts as a peak because it has nothing to compare against. A square that ties with any neighbour is not a peak. Return how many peaks the map contains.
Constraints: 1 <= m, n <= 50 and 0 <= grid[i][j] <= 10^4. Checking each cell against its neighbours takes O(m*n) time and O(1) extra space.
Example 1
- Input:
- grid = [[1,2,1],[2,5,2],[1,2,1]]
- Output:
- 1
- Explanation:
Only the centre 5 beats all four neighbours; the 2s each have the larger 5 beside them.
Example 2
- Input:
- grid = [[3,1,3],[1,0,1],[3,1,3]]
- Output:
- 4
- Explanation:
All four corners (3) are strictly larger than their two neighbours, so there are 4 peaks.
Example 3
- Input:
- grid = [[7,7],[7,7]]
- Output:
- 0
- Explanation:
Equal neighbours block every cell, so nothing is a strict peak and the answer is 0.
Constraints
1 ≤ m, n ≤ 50
0 ≤ grid[i][j] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(m*n)
- Space
- O(1)