Map of Highest Peak - Problem

You are given an integer matrix isWater of size m x n that represents a map of land and water cells.

If isWater[i][j] == 0, cell (i, j) is a land cell.
If isWater[i][j] == 1, cell (i, j) is a water cell.

You must assign each cell a height in a way that follows these rules:

  • The height of each cell must be non-negative.
  • If the cell is a water cell, its height must be 0.
  • Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).

Find an assignment of heights such that the maximum height in the matrix is maximized.

Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.

Input & Output

Example 1 — Basic Island
$ 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 distance 2 from water, so height 2.
Example 2 — Multiple Water Sources
$ Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]
Output: [[1,1,0],[0,1,1],[1,2,2]]
💡 Note: Two water cells at (0,2) and (1,0). Heights are minimum distance to any water cell.
Example 3 — All Water
$ Input: isWater = [[1,1],[1,1]]
Output: [[0,0],[0,0]]
💡 Note: All cells are water, so all heights are 0.

Constraints

  • m == isWater.length
  • n == isWater[i].length
  • 1 ≤ m, n ≤ 1000
  • isWater[i][j] is 0 or 1
  • There is at least one water cell

Visualization

Tap to expand
Map of Highest Peak - BFS Approach INPUT isWater Matrix (2x2) 0 Land 1 Water 0 Land 0 Land = Water (1) = Land (0) isWater = [[0,1],[0,0]] (0,0) (0,1) ALGORITHM STEPS 1 Initialize Queue Add water cells, height=0 Q: [(0,1)] 2 BFS Expansion Process neighbors level by level Level 0: (0,1) height=0 Level 1: (0,0),(1,1) height=1 3 Set Heights height = distance from water Level 2: (1,0) height=2 4 Complete All cells assigned, max=2 FINAL RESULT Height Matrix (2x2) 1 0 2 1 Height color scale: 0 1 2 Output: [[1,0],[2,1]] Max Height = 2 OK Key Insight: BFS from water cells guarantees minimum distance to nearest water, which equals optimal height. Adjacent cells differ by exactly 1 (BFS level difference), maximizing the highest peak. Time: O(m*n) | Space: O(m*n) for the queue and result matrix. TutorialsPoint - Map of Highest Peak | BFS Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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