Map of Highest Peak LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> highestPeak(vector<vector<int>> &isWater) {
4
int r = isWater.size();
5
int c = isWater[0].size();
6
queue<pair<int, int>> curr;
7

8
for (int i = 0; i < r; i++) {
9
for (int j = 0; j < c; j++) {
10
// set the land cell to -1 (not visited)
11
if (isWater[i][j] == 0) {
12
isWater[i][j] = -1;
13
}
14
// set the water cell to zero and to queue
15
else {
16
isWater[i][j] = 0;
17
curr.push({i, j});
18
}
19
}
20
}
21

22
int hill = 0;
23
while (!curr.empty()) {
24
int len = curr.size();
25

26
for (int k = 0; k < len; k++) {
27
// for each cell check its 4 boundary cells
28
// if it is not visited, increase its hill by 1
29
pair<int, int> fnt = curr.front();
30
curr.pop();
31
int i = fnt.first, j = fnt.second;
32

33
// top cell
34
if (i > 0 && isWater[i - 1][j] == -1) {
35
isWater[i - 1][j] = hill + 1;
36
curr.push({i - 1, j});
37
}
38
// bottom cell
39
if ((i < r - 1) && (isWater[i + 1][j] == -1)) {
40
isWater[i + 1][j] = hill + 1;
41
curr.push({i + 1, j});
42
}
43
// left cell
44
if (j > 0 && (isWater[i][j - 1] == -1)) {
45
isWater[i][j - 1] = hill + 1;
46
curr.push({i, j - 1});
47
}
48
// right cell
49
if ((j < c - 1) && (isWater[i][j + 1] == -1)) {
50
isWater[i][j + 1] = hill + 1;
51
curr.push({i, j + 1});
52
}
53
}
54

55
// after 1 complete round increase the height of the hill
56
hill += 1;
57
}
58

59
return isWater;
60
}
61
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0