Map of Highest Peak Problem
Description
LeetCode Problem 1765.
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*.
Example 1:

Input: isWater = [[0,1],[0,0]]
Output: [[1,0],[2,1]]
Explanation: The image shows the assigned heights of each cell.
The blue cell is the water cell, and the green cells are the land cells.
Example 2:

Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]
Output: [[1,1,0],[0,1,1],[1,2,2]]
Explanation: A height of 2 is the maximum possible height of any assignment.
Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.
Constraints:
m == isWater.lengthn == isWater[i].length1 <= m, n <= 1000isWater[i][j]is0or1.- There is at least one water cell.
Note: This question is the same as 542: https://leetcode.com/problems/01-matrix/
Solution
Approach: Multi-Source BFS
Every water cell must have height 0 and adjacent cells may differ by at most 1, so a land cell can be at most as high as its distance to the nearest water cell. Choosing exactly that distance for every cell is valid and gives the highest possible peak. Compute it with a BFS that starts from all water cells at once: each newly reached cell gets the height of its neighbour plus one.
Complexity: O(m × n) time and space.
from collections import deque
class Solution:
def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:
m, n = len(isWater), len(isWater[0])
ans = [[-1] * n for _ in range(m)]
q = deque()
for i, row in enumerate(isWater):
for j, v in enumerate(row):
if v:
q.append((i, j))
ans[i][j] = 0
while q:
i, j = q.popleft()
for a, b in zip((-1, 0, 1, 0), (0, 1, 0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and ans[x][y] == -1:
ans[x][y] = ans[i][j] + 1
q.append((x, y))
return ans