在二维数组元素之间的距离 [英] Distance between elements in 2D array

查看:392
本文介绍了在二维数组元素之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能确定一个二维数组1的之间的距离。例如,我们有一个二维数组是这样的:

How can I determine the distance between 1's in a 2D array. For example, we have a 2D array like this:

0 0 0 0
0 0 0 1
1 0 0 0
1 0 0 0

该算法,以输出从每个元素到最近1.筛选的距离:

The algorithm has to output the distance from each element to the nearest 1. Like this:

2 3 2 1
1 2 1 0
0 1 2 1
0 1 2 2

我该如何解决呢?

How can I solve it ?

推荐答案

您可以遍历矩阵,并找到所有的1,(X1,Y1)的坐标。然后在细胞中的列表中的每个位置(X2,Y2),对于所有(X1,Y1),找出最小|×2 - X1 | + | Y2 - Y1 | (因为它的曼哈顿距离是一个网格)。

You can iterate over the matrix and find the coordinates of all the 1's (x1, y1). Then for each position in the cell (x2, y2), for all (x1, y1) in your list, find the minimum |x2 - x1| + |y2 - y1| (the Manhattan distance since it's a grid).

这篇关于在二维数组元素之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆