Take the 2-minute tour ×

I have 2D array and want to convert it into 1D array.

The 2D array is:

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16

to 1D array:


How do I access nearest neighbor of the element number 6 in 1D array, so that I can get the same result when I access in 2D array, such as

1   2   3   
5   6   7   
9   10  11

in C++?

share|improve this question
With arithmetic. Old indexing m[1][2] new indexing m[1*4+2]. Old nearest neighbor [x-1][y-1],[x][y-1],x[x+1][y] etc., new: [(x-1)+4*(y-1)],[x+4*(y-1)],[x+1+4*(y-1)]. Replace 4 for the width of your array. –  user786653 Oct 22 '11 at 19:58
Thanks it is working. –  taker Oct 22 '11 at 20:50
add comment

1 Answer

If you have a 2D array that is M items long by N items tall, you need a 1D array that has M*N elements.

When trying to find the neighbors of element x:

left(x) = (x - 1) % M
right(x) = (x + 1) % M
above(x) = (x - M) % (M * N)
below(x) = (x + M) % (M * N)

Note that the above solution makes the bottom and top of your array adjacent, as well as the right edge and left edge. To get rid of that, simply omit the modular math and detect when your index has moved past the right / left / top / bottom edges.

share|improve this answer
I am sorry but I can't understand your solution. Would you enlighten me? –  taker Oct 22 '11 at 20:49
If you are looking at array location x, then the neighbor to the left is at x-1. The neighbor to the right is at x+1. The neighbor above you is at x-M. The neighbor below you is at x+M. This assumes that your vertical axis increases as you go down. If you want it to decrease, then swap the math for above and below. The re is literal edge case - how do you want to handle neighbors when you reach the top, bottom, left, or right edge? –  ObscureRobot Oct 23 '11 at 0:09
add comment

Your Answer


