Find neighbours outside of 2d grid which is reduce

2019-06-14 04: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条回答
贼婆χ
2楼-- · 2019-06-14 04:54

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

查看更多
登录 后发表回答