1481. Hilltop in the Grid
A surveyor records the altitude of every cell of a rectangular map as the matrix grid; all altitudes are different. A cell is a hilltop if its altitude is strictly greater than that of each of its neighbours, where a cell has up to eight neighbours (horizontal, vertical and diagonal) that lie inside the map.
Return [row, col] (0-indexed) of any hilltop. One always exists, because the highest cell overall qualifies. Any valid answer is accepted. To search in O(m log n) time rather than scanning everything, binary search over the columns: look at the maximum of the middle column and move toward the neighbouring column whose maximum is larger. Use O(1) extra space.
Example 1
- Input:
- grid = [[1,4,3],[5,9,2],[7,6,8]]
- Output:
- [1,1]
- Explanation:
The 9 at row 1, column 1 beats all eight cells around it, so [1,1] is accepted.
Example 2
- Input:
- grid = [[17]]
- Output:
- [0,0]
- Explanation:
A lone cell has no neighbours, so it is trivially a hilltop.
Example 3
- Input:
- grid = [[3,8,5,1],[2,4,9,6],[7,1,2,3]]
- Output:
- [1,2]
- Explanation:
The 9 at [1,2] is a hilltop; the 7 at [2,0] also beats all its neighbours, and either answer is accepted.
Constraints
1 ≤ m, n ≤ 30
1 ≤ grid[i][j] ≤ 106
All values in grid are distinct.
How this problem is judged
- Answers
- Any valid answer is accepted. A checker tests yours against the problem's rules.
Expected complexity
- Time
- O(m log n)
- Space
- O(1)