有没有更有效的方法来沿条件路径标记元素?

时间:2019-05-01 13:43:49

标签: python numpy

我正在尝试计算元素与数组中起点之间的距离。

这是一个数组

enter image description here

假设元素(0,1)是当前值最高的起点。

如果邻居具有相同的一个轴,并且在另一个轴上相差1个单位,则邻居是围绕特定点的元素,邻居和该点都必须具有值1。

通常,邻居可以是数组内部特定点的顶部,底部,左侧,右侧。

任务是用距离值标记每个元素,该距离值指示距起点(0,1)的距离。

ds = np.array([[1, 2, 1],
       [1, 1, 0],
       [0, 1, 1]])

dist = np.full_like(ds, -1)
p0 = np.where(ds == 2)
dist[p0] = 0
que = []
que.append(p0)
nghb_x = [0, 0, -1, 1]
nghb_y = [-1, 1, 0, 0]

while len(que):
    x, y = que.pop()
    d = dist[(x,y)]
    for idx0, idx1 in zip(nghb_x, nghb_y):
        tmp_x = x + idx0
        tmp_y = y + idx1
        if np.any(ds[tmp_x,tmp_y]==1) and np.any(tmp_x >= 0) and np.any(tmp_x < ds.shape[0]) and np.any(tmp_y >= 0) and np.any(tmp_y < ds.shape[1]) and np.any(dist[(tmp_x,tmp_y)] == -1):
            dist[(tmp_x,tmp_y)] = d + 1 # distance = distance(x) + 1
            que.append((tmp_x, tmp_y))

print('dist:')
print(dist[:-1,:-1])

输出

dist:
[[ 1  0  1]
 [ 2  1 -1]
 [-1  2  3]]

尽管如此,但我想知道是否有更有效的方法吗?

此任务与此post不同,它没有条件值1。

最后一行print(dist[:-1,:-1])是删除填充。

0 个答案:

没有答案
相关问题