凸包
凸包(Convex Hull)是一个计算几何(图形学)中的概念。 在一个实数向量空间v中,对于给定集合X,所有包含X的凸集的交集S被称为X的凸包。 在二维欧几里得空间中,凸包可想象为一条刚好包著所有点的橡皮圈。 用不严谨的话来讲,给定二维平面上的点集,凸包就是将最外层的点连接起来构成的凸多边形,它能包含点集中所有的点。
凸包用最小的周长围住了给定的所有点。如果一个凹多边形围住了所有的点,它的周长一定不是最小。如下图,凸多边形在周长上一定是最优的。
Graham 扫描法
时间复杂度:O(nlogn)
思路:Graham扫描的思想是先找到凸包上的一个点,然后从那个点开始按逆时针方向逐个找凸包上的点,实际上就是进行极角排序,然后对其查询使用。
- 把所有点放在二维坐标系中,则纵坐标最小的点一定是凸包上的点,如图中的P0。
- 把所有点的坐标平移一下,使 P0 作为原点,如上图。
- 计算各个点相对于 P0 的幅角 α ,按从小到大的顺序对各个点排序。当 α 相同时,距离 P0 比较近的排在前面。例如上图得到的结果为 P1,P2,P3,P4,P5,P6,P7,P8。我们由几何知识可以知道,结果中第一个点 P1 和最后一个点 P8 一定是凸包上的点。
(以上是准备步骤,以下开始求凸包)
以上,我们已经知道了凸包上的第一个点 P0 和第二个点 P1,我们把它们放在栈里面。现在从步骤3求得的那个结果里,把 P1 后面的那个点拿出来做当前点,即 P2 。接下来开始找第三个点: - 连接P0和栈顶的那个点,得到直线 L 。看当前点是在直线 L 的右边还是左边。如果在直线的右边就执行步骤5;如果在直线上,或者在直线的左边就执行步骤6。
- 如果在右边,则栈顶的那个元素不是凸包上的点,把栈顶元素出栈。执行步骤4。
- 当前点是凸包上的点,把它压入栈,执行步骤7。
- 检查当前的点 P2 是不是步骤3那个结果的最后一个元素。是最后一个元素的话就结束。如果不是的话就把 P2 后面那个点做当前点,返回步骤4。
最后,栈中的元素就是凸包上的点了。
以下为用Graham扫描法动态求解的过程:
下面静态求解过程
代码实现
function convexHull(points: Point[]): Point[] {
if (points.length < 4) return points;
const pole = GeoPoint.getLeftBottomPoint(points);
points = points
.reduce((result, current) => {
result.push({
x: current.x - pole.x,
y: current.y - pole.y,
});
return result;
}, [] as Point[])
.filter(
(point) => !GeoPoint.pointEqual(point, GeoPoint.defaultPoint()),
points.sort((p1, p2) => {
const angle1 = Math.atan2(p1.y, p1.x);
const angle2 = Math.atan2(p2.y, p2.x);
return angle1 < angle2 ? -1 : 1;
})
);
const convexHullStack: Point[] = [{ x: 0, y: 0 }, points[0]];
let length = 1
for (let index = 1; index < points.length; index++) {
const current = points[index];
let permission = 1
while (permission > 0 && length >= 1) {
const v1 = GeoPoint.offset(p1, current);
const v2 = GeoPoint.offset(p1, convexHullStack[length - 2]);
permission = Math.atan2(
Vector.crossProduct2D(v2, v1),
Vector.dotProduct2D(v2, v1)
);
if (permission > 0) length--
}
convexHullStack[++length] = current
}
for (const point of convexHullStack) {
point.x += pole.x;
point.y += pole.y;
}
return convexHullStack;
}
}
工具类
class GeoPoint {
static offset(p1: Point, p2: Point): Point {
return { x: p2.x - p1.x, y: p2.y - p1.y };
}
static distance(p1: Point, p2: Point): number {
if (!p1 || !p2) return 0;
const x = p1.x - p2.x;
const y = p1.y - p2.y;
return Math.sqrt(x * x + y * y);
}
static getLeftBottomPoint(points: Point[]): Point {
let pole = points[0];
for (const point of points) {
if (point.y < pole.y || (point.y == pole.y && point.x < pole.x)) {
pole = point;
}
}
return pole;
}
static defaultPoint(): Point {
return {
x: 0,
y: 0,
};
}
static pointEqual(p1: Point, p2: Point) {
return p1.x == p2.x && p1.y == p2.y;
}
}
class Vector {
static crossProduct2D(p1: Point, p2: Point) {
return p1.x * p2.y - p1.y * p2.x;
}
static dotProduct2D(p1: Point, p2: Point) {
return p1.x * p2.x + p1.y * p2.y;
}
}
参考文献