[LeetCode] Erect the Fence II

1924. Erect the Fence II

You are given a 2D integer array trees where trees[i] = [xi, yi] represents the location of the ith tree in the garden.

You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle. A tree is considered enclosed if it is inside or on the border of the circle.

More formally, you must form a circle using the rope with a center (x, y) and radius r where all trees lie inside or on the circle and r is minimum.

Return the center and radius of the circle as a length 3 array [x, y, r]. Answers within 10-5 of the actual answer will be accepted.

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
54
55
56
57
58
59
60
61
62
63
64
65
struct Point {
double x, y;

Point operator-(const Point& other) const {
return {x - other.x, y - other.y};
}
};

class Solution {
double dist(Point& a, Point b){
auto dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx*dx + dy*dy);
}
double outer(Point& a, Point& b) {
return a.x * b.y - a.y * b.x;
}
double inner(Point& a) {
return a.x * a.x + a.y * a.y;
}
Point centerOf(Point& a, Point& b) {
return {(a.x + b.x) / 2, (a.y + b.y) / 2};
}
Point centerOf(Point& a, Point& b, Point& c){
Point aa = b - a, bb = c - a;
double c1 = inner(aa) * 0.5, c2 = inner(bb) * 0.5;
double d = outer(aa, bb);
double x = a.x + (c1 * bb.y - c2 * aa.y) / d;
double y = a.y + (c2 * aa.x - c1 * bb.x) / d;
return {x, y};
}
vector<double> solve(vector<Point>& A) {
Point p{0,0};
double r = 0;
int n = A.size();
for(int i = 0; i < n; i++) {
if(dist(p, A[i]) > r) {
p = A[i], r = 0;
for(int j = 0; j < i; j++) {
if(dist(p, A[j]) > r) {
p = centerOf(A[i], A[j]);
r = dist(p, A[i]);
for(int k = 0; k < j; k++) {
if(dist(p, A[k]) > r) {
p = centerOf(A[i], A[j], A[k]);
r = dist(p, A[k]);
}
}
}
}
}
}
return {p.x, p.y, r};
}
public:
vector<double> outerTrees(vector<vector<int>>& A) {
sort(begin(A), end(A));
A.erase(unique(begin(A), end(A)), end(A));
random_shuffle(begin(A), end(A));
vector<Point> p;
for(auto& a : A) {
p.push_back({1.0 * a[0], 1.0 * a[1]});
}
return solve(p);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/erect-the-fence-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.