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

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

问题描述

如何确定二维数组中 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

我该如何解决?

推荐答案

您可以遍历矩阵并找到所有 1 (x1, y1) 的坐标.然后对于单元格 (x2, y2) 中的每个位置,对于列表中的所有 (x1, y1),找到最小值 |x2 - 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天全站免登陆