【C++】点到多边形最近的距离

可直接复制粘贴

#include <iostream>
#include <vector>
#include <math.h>

typedef struct point{
    double x = 0.;
    double y = 0.;
}Point;

/**
 *@brief 计算两点之间的距离
 *@param p1 坐标点1
 *@param p2 坐标点2
 *@return 两点距离
*/
double Distance(Point p1, Point p2) {
    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}

/**
 *@brief 计算点到直线的距离
 *@param p 点
 *@param l1,l2 直线坐标
 *@return 距离
*/
double PointToStraightDistance(Point p, Point l1, Point l2) {
    double a = Distance(l1, l2);
    double b = Distance(l1, p);
    double c = Distance(l2, p);
    if (b * b >= a * a + c * c) {
        return c;
    }
    if (c * c >= a * a + b * b) {
        return b;
    }
    double p0 = (a + b + c) / 2;
    double s = sqrt(p0 * (p0 - a) * (p0 - b) * (p0 - c));
    return 2 * s / a;
}

/**
 *@brief 点到多边形最近的距离
 *@param p 点
 *@param polygon 多边形坐标列表
 *@return 最近的距离
*/
double ClosestDistance(Point p, std::vector<Point> polygon)
{
    double minDistance = PointToStraightDistance(p, polygon[0], polygon[polygon.size() - 1]);
    for (int i = 0; i < polygon.size() - 1; i++) {
        double distance = PointToStraightDistance(p, polygon[i], polygon[i + 1]);
        if (distance < minDistance) {
            minDistance = distance;
        }
    }
    return minDistance;
}

int main()
{
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值