You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何实现GetNeighbors方法获取固定坐标点指定距离内的邻域点

实现思路

你的现有代码里的双重循环思路是反过来的,不需要遍历邻域内的所有坐标点去匹配点集,直接遍历传入的点集,逐个判断坐标是否在邻域范围内即可,效率更高,也更易实现。

现有逻辑问题修正

  1. 你当前写的y轴循环条件for (int y = top; y <= bottom; y++)永远不会执行,因为top是目标点Y坐标加h,值大于bottom(Y减h),初始值已经大于循环终止条件
  2. 不需要生成邻域内所有整数坐标,直接用Point结构体公开的X、Y属性判断点集内的点是否符合范围要求即可

完整修正代码

/// <summary>
/// 从给定的点集中筛选出与整数坐标(x,y)的目标点相距h以内的h邻域点
/// </summary>
/// <param name="point">目标整数坐标点</param>
/// <param name="h">邻域距离阈值</param>
/// <param name="points">待筛选的点集</param>
/// <returns>符合要求的h邻域点集合</returns>
/// <exception cref="ArgumentNullException">点集为null时抛出</exception>
/// <exception cref="ArgumentException">h小于等于0时抛出</exception>
public static Point[] GetNeighbors(Point point, int h, params Point[] points)
{
    if (points is null)
    {
        throw new ArgumentNullException(nameof(points));
    }

    if (h <= 0)
    {
        throw new ArgumentException("h必须大于0", nameof(h));
    }

    List<Point> neighbors = new List<Point>();

    int left = point.X - h;
    int right = point.X + h;
    int bottom = point.Y - h;
    int top = point.Y + h;

    // 直接遍历传入的点集做判断
    foreach (Point p in points)
    {
        // 轴对齐正方形邻域(切比雪夫距离≤h)判断逻辑,和你预设的边界完全匹配
        if (p.X >= left && p.X <= right && p.Y >= bottom && p.Y <= top)
        {
            neighbors.Add(p);
        }

        // 如果要求欧氏距离≤h,把上面的判断替换为下方逻辑即可,用平方比较避免开方损耗
        // int dx = p.X - point.X;
        // int dy = p.Y - point.Y;
        // if (dx * dx + dy * dy <= h * h)
        // {
        //     neighbors.Add(p);
        // }
    }

    return neighbors.ToArray();
}

补充说明

你定义的Point结构体已经公开了X和Y的只读属性,直接访问即可读取坐标值,不需要额外转换或者特殊操作。如果需要判断两个点是否完全相等,直接用==运算符即可,你已经重载了对应的运算符逻辑。

邻域范围示意图

neighborhood

内容的提问来源于stack exchange,提问作者Linascts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:06:03