587. Erect the Fence(安装栅栏)

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://leetcode-cn.com/problems/erect-the-fence

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;
        // get the left most point
        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;
    //intialize the vector trees with [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
    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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值