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.
Convex Hull
def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
def ccw(p1, p2, p3):
v1x = p2[0] - p1[0]
v1y = p2[1] - p1[1]
v2x = p3[0] - p2[0]
v2y = p3[1] - p2[1]
res = (v1x * v2y - v2x * v1y)
if res > 0:
return 1
elif res == 0:
return 0
else:
return -1
trees.sort()
def compute_hull(target):
upper = []
for i in range(len(trees)):
upper.append(i)
while len(upper) >= 3 and ccw(trees[upper[-3]], trees[upper[-2]], trees[upper[-1]]) not in target:
last = upper.pop()
upper.pop()
upper.append(last)
return upper
upper = compute_hull([0, -1])
lower = compute_hull([0, 1])
lower.reverse()
return [trees[i] for i in set(upper + lower[1:-1])]