【发布时间】:2021-01-24 00:26:38
【问题描述】:
我在尝试在 python 中提出一个简单的方形网格查找时画了一个空白,希望有人可以在这里给我一些指示。假设我有一个 5x5 网格,从中心 (3,3) 开始,我希望查找增加半径输出外围坐标,如下所示:
Radius Output
0 [[3,3]]
1 [[2,2], [2,3], [2,4], [3,2], [3,4], [4,2], [4,3], [4,4]]
2 [[1,1], [1,2], [1,3], [1,4], [1,5], [2,1], [2,5], [3,1],
[3,5], [4,1], [4,5], [1,1], [1,2], [1,3], [1,4], [1,5]]
任何指针将不胜感激!
更新:我目前的代码是:
center_coordinate = [3, 3]
completed_locations = [center_coordinate]
radius = 0
max_radius = 3
while radius != max_radius:
x_grid = [x for x in range(center_coordinate[0] - radius, center_coordinate[0] + radius + 1)]
y_grid = [y for y in range(center_coordinate[0] - radius, center_coordinate[0] + radius + 1)]
locations = []
for x in x_grid:
for y in y_grid:
if [x, y] not in completed_locations:
locations.append([x, y])
completed_locations.append([x, y])
radius += 1
print(radius, locations)
虽然这确实可以完成工作,但我正在寻找一种解决方案,它不需要我在迭代时交叉检查每个位置。我要处理的实际网格大小是 750x750,这个特定的模块将定期被召唤。
【问题讨论】:
-
你什么都想不出来?比如:1) 计算中心坐标 x0, y0 2) 获取坐标 x0+/-1, y0+/-1, 3) 获取所有单元格 x0+/-2, y0+/-2...?
标签: python-3.x