Find all integer coordinates in a given radius

前端 未结 4 919
臣服心动
臣服心动 2020-12-31 18:09

Given a two-dimensional coordinate system how can I find all points with integer coordinates in a radius from a given point? I want the points as x-coordinate and y-coordina

4条回答
  •  伪装坚强ぢ
    2020-12-31 19:00

    You can make a small modification to the midpoint circle algorithm to get a filled circle.

    First generate the coordinates:

    data = new int[radius];
    int f = 1 - radius, ddF_x = 1;
    int ddF_y = -2 * radius;
    int x = 0, y = radius;
    while (x < y)
    {
        if (f >= 0)
        {
            y--;
            ddF_y += 2; f += ddF_y;
        }
        x++;
        ddF_x += 2; f += ddF_x;
        data[radius - y] = x; data[radius - x] = y;
    }
    

    Then visit all the interior points:

    int x0 = center.X;
    int y0 = center.Y - Radius;
    int y1 = center.Y + Radius - 1;
    
    for (int y = 0; y < data.Length; y++)
    {
        for (int x = -data[y]; x < data[y]; x++)
        {
            doSomething(x + x0, y + y0);
            doSomething(x + x0, y1 - y);
        }
    }
    

    That saves some work visiting points that won't be in the circle, but at the expense of a little pre-processing. It definitely won't help for smaller circles, and for bigger ones, well, I honestly don't know. You'd have to benchmark it.

提交回复
热议问题