[LeetCode] Map of Highest Peak

1765. Map of Highest Peak

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
vector<vector<int>> highestPeak(vector<vector<int>>& A) {
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
int n = A.size(), m = A[0].size();

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == 0) A[i][j] = -1;
else if(A[i][j] == 1) A[i][j] = 0;
}
}

queue<pair<int,int>> q;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == -1) continue;
for(int k = 0; k < 4; k++) {
int ny = i + dy[k], nx = j + dx[k];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx] == -1)
q.push({ny,nx});
}
}
}
while(!q.empty()) {
queue<pair<int, int>> qq;
while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
int mi = INT_MAX;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx] >= 0) {
mi = min(mi, A[ny][nx]);
}
}
A[y][x] = mi + 1;
qq.push({y, x});
}
while(!qq.empty()) {
auto [y, x] = qq.front(); qq.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx] == -1) {
q.push({ny, nx});
A[ny][nx] = -2;
}
}
}
}

return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/01/PS/LeetCode/map-of-highest-peak/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.