Description of problem
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located on the fence perimeter.
来源:力扣(LeetCode)
链接:https:
Chinese version
在一个二维的花园中,有一些用 (x, y) 坐标表示的树。
由于安装费用十分昂贵,你的任务是先用最短的绳子围起所有的树。
只有当所有的树都被绳子包围时,花园才能围好栅栏。你需要找到正好位于栅栏边界上的树的坐标。
The intuition for this problem
Jarvis 算法
The codes for this problem
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int cross(vector<int>& A, vector<int>& B, vector<int>& C) {
return (B[0]-A[0])*(C[1]-A[1]) - (C[0]-A[0])*(B[1]-A[1]);
}
vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
int n = trees.size();
if (n < 4) return trees;
vector<vector<int>> ans;
int left_most = 0;
for (int i = 0; i < n; ++i) {
if (trees[i][0] < trees[left_most][0]) {
left_most = i;
}
}
int cur = left_most;
vector<bool> visited(n, false);
visited[cur] = true;
ans.emplace_back(trees[cur]);
do{
int next = (cur + 1) % n;
for (int i = 0; i < n; ++i) {
if (cross(trees[cur], trees[next], trees[i]) < 0) {
next = i;
}
}
for (int k = 0; k < n; ++k) {
if (visited[k] || k == cur || k == next) continue;
if (cross(trees[cur], trees[next], trees[k]) == 0) {
ans.emplace_back(trees[k]);
visited[k] = true;
}
}
if (!visited[next]) {
visited[next] = true;
ans.emplace_back(trees[next]);
}
cur = next;
} while (cur != left_most);
return ans;
}
};
int main()
{
Solution s;
vector<vector<int>> trees = {{1,1},{2,2},{2,0},{2,4},{3,3},{4,2}};
vector<vector<int>> ans = s.outerTrees(trees);
for (auto& v : ans) {
for (auto& i : v) {
cout << i << " ";
}
cout << endl;
}
return 0;
}
The outputs
1 1
2 0
4 2
3 3
2 4
|