42 lines
1.1 KiB
C
42 lines
1.1 KiB
C
|
#include <stdlib.h>
|
|||
|
|
|||
|
// 定义一个点结构体
|
|||
|
typedef struct {
|
|||
|
int x, y;
|
|||
|
} Point;
|
|||
|
|
|||
|
// 计算两点的极角
|
|||
|
int orientation(Point p, Point q, Point r) {
|
|||
|
int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
|
|||
|
if (val == 0) return 0; // 共线
|
|||
|
return (val > 0) ? 1 : 2; // 顺时针或逆时针
|
|||
|
}
|
|||
|
|
|||
|
// 对点的极角排序
|
|||
|
int compare(const void *vp1, const void *vp2) {
|
|||
|
Point *p1 = (Point *)vp1;
|
|||
|
Point *p2 = (Point *)vp2;
|
|||
|
return (p1->y < p2->y) || (p1->y == p2->y && p1->x < p2->x);
|
|||
|
}
|
|||
|
|
|||
|
// 凸包主函数
|
|||
|
void convexHull(Point points[], int n, Point result[], int *result_size) {
|
|||
|
// 如果点数小于 3,无法构成凸包
|
|||
|
if (n < 3) {
|
|||
|
*result_size = 0;
|
|||
|
return;
|
|||
|
}
|
|||
|
|
|||
|
// 按 y 坐标排序,如果 y 坐标相同则按 x 坐标排序
|
|||
|
qsort(points, n, sizeof(Point), compare);
|
|||
|
|
|||
|
// 构建凸包
|
|||
|
int m = 0; // 凸包的点数
|
|||
|
for (int i = 0; i < n; i++) {
|
|||
|
while (m >= 2 && orientation(result[m-2], result[m-1], points[i]) != 2)
|
|||
|
m--;
|
|||
|
result[m++] = points[i];
|
|||
|
}
|
|||
|
|
|||
|
*result_size = m;
|
|||
|
}
|