Formatted question description: https://leetcode.ca/all/587.html

587. Erect the Fence

Level

Hard

Description

There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is 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. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.

Example 1:

Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]

Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]

Explanation:

Image text

Example 2:

Input: [[1,2],[2,2],[4,2]]

Output: [[1,2],[2,2],[4,2]]

Explanation:

Image text

Even you only have trees in a line, you need to use rope to enclose them.

Note:

  1. All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.
  2. All input integers will range from 0 to 100.
  3. The garden has at least one tree.
  4. All coordinates are distinct.
  5. Input points have NO order. No order required for output.
  6. Input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

Solution

Use Jarvis algorithm to find the convex hull. Starting from the leftmost point, consider all the points on the fence in counterclockwise direction. For each point p, find point q that is the closest to p in the counterclockwise direction, and point q is on the fence. When the start point is met, the fence is completed.

  • class Solution {
        public int[][] outerTrees(int[][] points) {
            int length = points.length;
            if (length < 4)
                return points;
            Arrays.sort(points, new Comparator<int[]>() {
                public int compare(int[] point1, int[] point2) {
                    if (point1[0] != point2[0])
                        return point1[0] - point2[0];
                    else
                        return point1[1] - point2[1];
                }
            });
            List<int[]> hullList = new ArrayList<int[]>();
            Set<String> hullSet = new HashSet<String>();
            int p = 0;
            do {
                int q = (p + 1) % length;
                for (int i = 0; i < length; i++) {
                    if (orientation(points[p], points[i], points[q]) < 0)
                        q = i;
                }
                for (int i = 0; i < length; i++) {
                    if (i == p || i == q)
                        continue;
                    if (orientation(points[p], points[i], points[q]) == 0 && isBetween(points[i], points[p], points[q])) {
                        if (hullSet.add(Arrays.toString(points[i])))
                            hullList.add(points[i]);
                    }
                }
                if (hullSet.add(Arrays.toString(points[q])))
                    hullList.add(points[q]);
                p = q;
            } while (p != 0);
            int hullLength = hullList.size();
            int[][] hullArray = new int[hullLength][2];
            for (int i = 0; i < hullLength; i++) {
                int[] hull = hullList.get(i);
                for (int j = 0; j < 2; j++)
                    hullArray[i][j] = hull[j];
            }
            return hullArray;
        }
    
        public int orientation(int[] point1, int[] point2, int[] point3) {
            return (point2[0] - point1[0]) * (point3[1] - point2[1]) - (point3[0] - point2[0]) * (point2[1] - point1[1]);
        }
    
        public boolean isBetween(int[] point, int[] point1, int[] point2) {
            boolean xBetween = point[0] >= point1[0] && point[0] <= point2[0] || point[0] <= point1[0] && point[0] >= point2[0];
            boolean yBetween = point[1] >= point1[1] && point[1] <= point2[1] || point[1] <= point1[1] && point[1] >= point2[1];
            return xBetween && yBetween;
        }
    }
    
  • Todo
    
  • # Definition for a point.
    # class Point(object):
    #     def __init__(self, a=0, b=0):
    #         self.x = a
    #         self.y = b
    
    class Solution(object):
      def outerTrees(self, points):
        """
        :type points: List[Point]
        :rtype: List[Point]
        """
        if len(points) == 1:
          return points
    
        def direction(p, q, r):
          return ((p.x - r.x) * (q.y - r.y) - (p.y - r.y) * (q.x - r.x))
    
        points.sort(key=lambda x: (x.x, x.y))
        upper = []
        lower = []
        for point in points:
          while len(lower) >= 2 and direction(lower[-2], lower[-1], point) < 0:
            lower.pop()
          lower.append(point)
    
        for point in reversed(points):
          while len(upper) >= 2 and direction(upper[-2], upper[-1], point) < 0:
            upper.pop()
          upper.append(point)
    
        return list(set(upper[1:] + lower[1:]))
    
    

All Problems

All Solutions