Map of Highest Peak - Problem
Map of Highest Peak - Create an optimal height map that maximizes the peak elevation!

You're given a matrix representing land and water cells on a map. Your task is to assign heights to each cell following specific rules:

๐ŸŒŠ Water cells (value = 1) must have height 0
๐Ÿ”๏ธ Land cells (value = 0) can have any non-negative height
๐Ÿ“ Adjacent cells can differ in height by at most 1

The goal is to maximize the highest peak in the entire map. Think of it as creating the most dramatic mountain landscape possible while respecting the physical constraints!

Example: If you have water in the center and land around it, the land cells closest to water will be height 1, the next layer will be height 2, and so on, creating natural-looking mountain ridges.

Input & Output

example_1.py โ€” Basic 2x2 Grid
$ Input: isWater = [[0,1],[0,0]]
โ€บ Output: [[1,0],[2,1]]
๐Ÿ’ก Note: Water cell at (0,1) has height 0. Adjacent cells get height 1. Cell (1,0) is farthest from water, so it gets height 2.
example_2.py โ€” 3x3 Grid with Center Water
$ Input: isWater = [[0,0,1],[0,0,0],[0,0,0]]
โ€บ Output: [[2,1,0],[3,2,1],[4,3,2]]
๐Ÿ’ก Note: Water is at top-right. Heights increase as we move away from water, creating a diagonal pattern with maximum height 4.
example_3.py โ€” All Water
$ Input: isWater = [[1,1],[1,1]]
โ€บ Output: [[0,0],[0,0]]
๐Ÿ’ก Note: All cells are water, so all heights are 0. This is an edge case where no land cells exist.

Constraints

  • m == isWater.length
  • n == isWater[i].length
  • 1 โ‰ค m, n โ‰ค 1000
  • isWater[i][j] is 0 or 1
  • At least one cell is a water cell

Visualization

Tap to expand
01234Water โ†’ Land โ†’ Hills โ†’ Mountains โ†’ PeaksBFS ensures optimal height assignment in O(mn) time
Understanding the Visualization
1
Water Foundation
All water cells start at elevation 0 (sea level)
2
First Ridge
Land cells touching water get elevation 1
3
Higher Peaks
Each subsequent layer gets +1 elevation
4
Maximum Heights
Cells farthest from any water become the highest peaks
Key Takeaway
๐ŸŽฏ Key Insight: Multi-source BFS naturally computes the shortest distance (optimal height) from each cell to the nearest water source, creating the tallest possible mountain landscape while respecting adjacency constraints.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
38.3K Views
Medium Frequency
~15 min Avg. Time
1.8K 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