Loading problem...
You are given an integer matrix terrainMap of dimensions m × n that represents a geographical map consisting of ground cells and water cells.
terrainMap[i][j] == 0, the cell at position (i, j) is a ground cell.terrainMap[i][j] == 1, the cell at position (i, j) is a water cell.Your task is to assign an elevation value to each cell in the grid according to the following rules:
0.1.Return an integer matrix elevations of the same dimensions m × n, where elevations[i][j] represents the assigned elevation of cell (i, j). If multiple valid solutions exist that achieve the maximum possible peak elevation, you may return any of them.
Key Insight: The optimal elevation for each ground cell equals its shortest distance (in terms of orthogonal moves) to the nearest water cell. This ensures adjacent cells differ by at most 1 while maximizing the overall heights.
terrainMap = [[0,1],[0,0]][[1,0],[2,1]]The water cell is at position (0,1) with elevation 0. Cell (0,0) is 1 step away from water, so its elevation is 1. Cell (1,1) is also 1 step away from the water cell at (0,1), so elevation is 1. Cell (1,0) is 2 steps away from the nearest water cell (via (0,0) or (1,1)), so its elevation is 2. The maximum elevation achieved is 2.
terrainMap = [[0,0,1],[1,0,0],[0,0,0]][[1,1,0],[0,1,1],[1,2,2]]There are two water cells: (0,2) and (1,0), both with elevation 0. Each ground cell is assigned an elevation equal to its minimum distance to any water cell. For example, cell (2,2) is 2 steps from cell (0,2), so its elevation is 2. The maximum elevation in this configuration is 2.
terrainMap = [[0,0,0],[0,1,0],[0,0,0]][[2,1,2],[1,0,1],[2,1,2]]The single water cell is at the center (1,1) with elevation 0. All cells directly adjacent to it have elevation 1, and the corner cells have elevation 2 since they are 2 steps away from the water source. The grid forms a symmetric elevation pattern radiating outward from the center.
Constraints