Find neighbours outside of 2d grid which is reduced into a 1d array

♀尐吖头ヾ 提交于 2019-12-08 13:55:53

问题


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?

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?


回答1:


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.

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).



来源:https://stackoverflow.com/questions/35818063/find-neighbours-outside-of-2d-grid-which-is-reduced-into-a-1d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!