找到二维网格以外邻居被还原成一维数组 [英] Find neighbours outside of 2d grid which is reduced into a 1d array
问题描述
我有一个二维方格,宽度和高度都是一样的。
I have a two dimensional grid where width and height are always the same.
[0][1][2]
[3][4][5]
[6][7][8]
我减少它的数据源到一个一维阵列
I reduced it's data source into a one-dimensional array.
[0][1][2][3][4][5][6][7][8]
元素的接入工作,但来这里的棘手的问题:如何才知道,小区的邻居是否网格的外部时仍在处理一维数组
Access of elements works, but here comes the tricky part: How to know, whether a neighbour of a cell is outside the grid when still processing the one-dimensional array?
例如[5]是出了电网的,但使用一个calculcated偏移索引右上邻居,我会得到[3]
For example the upper right neighbour of [5] is out of the grid but using a calculcated offset index, I will get [3].
与任何人在这方面的经验?
Anyone with experience in this field?
推荐答案
好吧假设你知道(i)于本小区和(2)网格的尺寸(明智的吧?),而且它的索引的索引一维数组是 K
和二维数组中的 I,J
。
Well assuming you know (i) the indices of the cell and (2) the dimensions of the grid (sensible right?), and that its index in the 1D array is k
, and in the 2D array i, j
.
然后 K = 1 *宽+ J
。因此, I = K /宽度
,Ĵ= K%宽度
。 ( /
是整数除法,%
为模数)。
Then k = i * width + j
. Thus i = k / width
, j = k % width
. (/
is integer division, %
is modulus).
一旦你得到这两个指数,你知道相邻小区的指数,你可以检查这些反对的界限为正常(我假设你懂得)。
Once you get these two indices, you know the neighboring cell's indices, and you can check those against the boundaries as normal (I assume you know how).
这篇关于找到二维网格以外邻居被还原成一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!