这是一种判断一个点是否在多边形内部的方法,叫做“交点法”。它的思想是:将该点围绕该点作一个大小为360度的圆,然后计算多边形与该圆的交点数量。如果该数量为奇数,则该点在多边形内,否则在外。
下面是代码实现:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const double Pi = 3.14159265358979323846;
struct Point {
double x, y;
};
// 计算两点间的距离
double dist(Point a, Point b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
// 计算两点间的夹角(弧度)
double angle(Point a, Point b) {
return atan2(b.y - a.y, b.x - a.x);
}
// 判断一个点是否在多边形内部
bool insidePolygon(Point p, vector<Point> polygon) {
int n = polygon.size();
int count = 0;
for (int i = 0; i < n; i++) {
Point a = polygon[i];
Point b = polygon[(i + 1) % n];
if (a.y > b.y) {
swap(a, b);
}
if (p.y < a.y || p.y > b.y) {
continue;
}
double angle = atan2(b.y - a.y, b.x - a.x) - atan2(p.y - a.y, p.x - a.x);
if (angle > Pi) {
angle = 2 * Pi - angle;
}
if (angle < 0) {
count++;
}
}
return count % 2 == 1;
}
int main() {
vector<Point> polygon = {{0, 0}, {0, 1}, {1, 1}, {1, 0}};
Point p = {0.5, 0.5};
cout << (insidePolygon(p, polygon) ? "inside" : "outside") << endl;
return 0;
}