Ctrl K

Land Heights Around Water

Medium
The map terrain is a rectangular grid: 1 marks a water cell and 0 a land cell. Give every cell an integer height following these rules: - heights are non-negative; - water has height 0; - cells sharing a side differ in height by at most 1. Under these rules each cell has a highest possible height, and all of them can be reached at once. Return the grid of heights where every cell is as high as it can be.
Example 1
terrain=[[1, 0, 0], [0, 0, 0]] → [[0, 1, 2], [1, 2, 3]]

Water sits only in the corner. Each land cell rises exactly to its step distance from it: neighbours get 1, then 2, and the far corner 3.

Example 2
terrain=[[0, 0, 0, 0], [1, 0, 0, 1]] → [[1, 2, 2, 1], [0, 1, 1, 0]]

Two water cells at both ends of the bottom row; the middle of the top row is farthest away and reaches height 2.

Constraints
  • 1 ≤ m, n ≤ 1000, where m and n are the numbers of rows and columns
  • Every cell is 0 or 1
  • At least one cell is water
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrain the Landlocked Ponds MediumLand Regions on a Map MediumSteps to the Nearest Exit MediumRain Reaching Both Seas MediumCan the Ball Stop at the Target Medium
loading Python…
Input
terrain=[[1, 0, 0], [0, 0, 0]]
Expected
[[0, 1, 2], [1, 2, 3]]

Run checks the first 3 tests in your browser. Submit checks all 70 tests on the server, hidden ones included.