繁体   English   中英

如何计算 Python 上二维网格中单元格之间的距离

[英]How to compute distance between cells in a 2D grid on Python

我的示例与问题Python 的示例接近:如何计算单元之间的距离? ,但我想要的是计算 2 个单元格之间的距离,同时考虑到相邻单元格之间的距离始终为 1(包括对角线)。 让我解释:

假设我有以下二维网格:

20  21  22  23  24
15  16  17  18  19
10  11  12  13  14
5   6   7   8   9
0   1   2   3   4

我想要的是一个 function 作为参数,它有 2 个单元格索引并返回它们之间的距离,因此相邻单元格之间的距离为 1(对角线单元格也相邻)。

我试过这样的事情:

import numpy as np
import numba as nb

@nb.njit # to speed up the code with numba
def distance(a,b,n=5):
    x1 = a%n;  x2 = b%n;
    y1 = a//n; y2 = b//n
    return np.floor(np.sqrt( (x1-x2)**2 + (y1-y2)**2 ))

但是,这适用于某些单元格,但不适用于其他单元格,例如:

>>> distance(2,7)
1.0 # works!
>>> distance(3,11)
2.0 # works!
>>> distance(0,24)
5.0 # wrong! it should be 4.0
>>> distance(0, 23)
5.0 # wrong! it should be also 4.0

我的意思是,我认为线性距离计算得很好,但对角线距离并不是全部

尝试:

def distance(a, b, n=5):
    x1 = a%n;  x2 = b%n;
    y1 = a//n; y2 = b//n
    dx = abs(x1 - x2)
    dy = abs(y1 - y2)
    return max([dx, dy])
>>> distance(2,7)
1
>>> distance(3,11)
2
>>> distance(0,24)
4
>>> distance(0, 23)
4

解释:

我们可以想象,如果我们想以尽可能短的距离从 a 点到达 b 点,我们首先要耗尽尽可能多的对角线移动。 如果没有对角线,我们将不得不进行dx + dy次移动,但是由于我们可以沿对角线方向移动,因此我们可以在一次移动中有效地在两个方向上移动。 这意味着两者中较小的一个( dxdy )变得无关紧要,因为如果dy = 10 和dx = 5,我们已经需要在垂直方向移动 10,因此我们可以通过隐藏其中的 5 个来捕获水平方向的 5 个移动垂直移动变成对角线移动。 因此,答案是max([dx, dy])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM