更新
有新信息:
假设对角坐标
距离 2 远
这个算法可以工作。该算法以一种螺旋方式向外搜索,从内部开始测试每个“环”中的每个点。
请注意,它不处理越界情况。所以你应该改变它以满足你的需要。
int xs, ys; // Start coordinates
// Check point (xs, ys)
for (int d = 1; d<maxDistance; d++)
{
for (int i = 0; i < d + 1; i++)
{
int x1 = xs - d + i;
int y1 = ys - i;
// Check point (x1, y1)
int x2 = xs + d - i;
int y2 = ys + i;
// Check point (x2, y2)
}
for (int i = 1; i < d; i++)
{
int x1 = xs - i;
int y1 = ys + d - i;
// Check point (x1, y1)
int x2 = xs + i;
int y2 = ys - d + i;
// Check point (x2, y2)
}
}
旧版本
假设在您的二维网格中,(0, 0) 和 (1, 0) 之间的距离与 (0, 0) 和 (1, 1) 之间的距离相同。该算法将起作用。该算法以一种螺旋方式向外搜索,从内部开始测试每个“环”中的每个点。
请注意,它不处理越界情况。所以你应该改变它以满足你的需要。
int xs, ys; // Start coordinates
if (CheckPoint(xs, ys) == true)
{
return (xs, ys);
}
for (int d = 0; d<maxDistance; d++)
{
for (int x = xs-d; x < xs+d+1; x++)
{
// Point to check: (x, ys - d) and (x, ys + d)
if (CheckPoint(x, ys - d) == true)
{
return (x, ys - d);
}
if (CheckPoint(x, ys + d) == true)
{
return (x, ys - d);
}
}
for (int y = ys-d+1; y < ys+d; y++)
{
// Point to check = (xs - d, y) and (xs + d, y)
if (CheckPoint(x, ys - d) == true)
{
return (xs - d, y);
}
if (CheckPoint(x, ys + d) == true)
{
return (xs - d, y);
}
}
}