[LeetCode] Finding the Number of Visible Mountains

2345. Finding the Number of Visible Mountains

You are given a 0-indexed 2D integer array peaks where peaks[i] = [xi, yi] states that mountain i has a peak at coordinates (xi, yi). A mountain can be described as a right-angled isosceles triangle, with its base along the x-axis and a right angle at its peak. More formally, the gradients of ascending and descending the mountain are 1 and -1 respectively.

A mountain is considered visible if its peak does not lie within another mountain (including the border of other mountains).

Return the number of visible mountains.

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
class Solution {
string toString(vector<int>& A) {
string res = "";
for(auto& a : A) res += to_string(a) + '#';
return res;
}
public:
int visibleMountains(vector<vector<int>>& peaks) {
int res = 0, n = peaks.size();
unordered_map<string, int> freq;
for(auto& p : peaks) freq[toString(p)]++;
vector<array<int,3>> A;
for(auto& p : peaks) {
if(freq[toString(p)] > 1) continue;
int x = p[0], y = p[1];
A.push_back({x-y,y,x+y});
}
sort(begin(A), end(A), [](auto a, auto b) {
if(a[0] == b[0]) return a[1] > b[1];
return a[0] < b[0];
});
int bound = -1;
for(auto& [l, h, r] : A) {
if(bound < r) {
res++;
bound = r;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/25/PS/LeetCode/finding-the-number-of-visible-mountains/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.