给定一个数组 trees
,其中 trees[i] = [xi, yi]
表示树在花园中的位置。
你被要求用最短长度的绳子把整个花园围起来,因为绳子很贵。只有把 所有的树都围起来,花园才围得很好。
返回恰好位于围栏周边的树木的坐标。
输入: points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] 输出: [[1,1],[2,0],[3,3],[2,4],[4,2]]
import scala.collection.mutable.ListBuffer
object ConvexHull {
def orientation(p: (Int, Int), q: (Int, Int), r: (Int, Int)): Int = {
val valOrient = (q._2 - p._2) * (r._1 - q._1) - (q._1 - p._1) * (r._2 - q._2)
if (valOrient == 0) 0 else if (valOrient > 0) 1 else 2
}
def convexHull(points: Array[(Int, Int)]): Array[(Int, Int)] = {
val n = points.length
if (n < 3) return points
// 找到最左边的点
var l = 0
for (i <- 1 until n) {
if (points(i)._1 < points(l)._1) l = i
}
val hull = ListBuffer[(Int, Int)]()
var p = l
var q = 0
do {
hull += points(p)
q = (p + 1) % n
for (i <- 0 until n) {
if (orientation(points(p), points(i), points(q)) == 2) {
q = i
}
}
p = q
} while (p != l)
hull.toArray
}
def main(args: Array[String]): Unit = {
val points = Array((1, 1), (2, 2), (2, 0), (2, 4), (3, 3), (4, 2))
val result = convexHull(points)
println(result.mkString("[", ", ", "]"))
}
}