查找二维网格之外的邻居,该网格被缩减为一维数组 [英] Find neighbours outside of 2d grid which is reduced into a 1d array

查看:28
本文介绍了查找二维网格之外的邻居,该网格被缩减为一维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维网格,其中宽度和高度始终相同.

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] 的右上角邻居不在网格中,但使用计算的偏移索引,我将得到 [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 = i * width + j.因此i = k/widthj = k % width.(/ 是整数除法,% 是模数).

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屋!

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