# Checking surrounding indexes of an index in a 2d array

• 03-30-2013, 11:23 AM
romero4742
Checking surrounding indexes of an index in a 2d array
Hey guys, I have a question on what may be a good way to check the surrounding indexes of a certain index of an array.
For example, if i want to check the surrounding indexes of the index 6 I want to check 1 2 3 5 7 9 a b

1 2 3 4
5 6 7 8
9 a b c

when I check the surrounding indexes I want to check if the object == null. If so, I want to check the surrounding indexes of that index.

so if 7 == null then check 2 3 4 8 c b a 6

I have thought of recursion but I know its not very efficient and should be avoided and I also got a stack overflow

this is the crap I wrote which I am not very proud of and definitely want to get rid of :(

Cheers

Code:

```    public void revealEmpty(int x ,int y)     {       if(x < 0 || x > mf.cols || y < 0 || y > mf.rows)           return;       if(mf.field[x][y] != null)           return;       buttons[x][y].setEnabled(false);       revealEmpty(x-1,y);       revealEmpty(x+1,y);       revealEmpty(x,y-1);       revealEmpty(x,y+1);       revealEmpty(x-1,y-1);       revealEmpty(x-1,y+1);       revealEmpty(x+1,y-1);       revealEmpty(x+1,y+1);     }```
• 03-30-2013, 12:10 PM
JosAH
Re: Checking surrounding indexes of an index in a 2d array
In your example you use a single index value, but in your code you use two index values (x and y); which is it?

kind regards,

Jos
• 03-31-2013, 07:39 AM
romero4742
Re: Checking surrounding indexes of an index in a 2d array
I think i did not explain my example right my bad but in my code I am passing in x, y which are the indexes for a 2d array. The array is in the mf object so when i say mf.field i refer to the array.

in my example i should have said
for index [1][1] I want to check [0][0], [0][1],[0][2],[1][0],[1][2],[2][0],[2][1],[2][2]

1 2 3 4
5 6 7 8
9 a b c

Sorry for the confusion
• 03-31-2013, 10:02 AM
JosAH
Re: Checking surrounding indexes of an index in a 2d array
For two dimensional indexes it's easy:

Code:

```for (int dx= -1; dx <= 1; dx++)   for (int dy= -1; dy <= 1; dy++)       if (!(dx == 0 && dy == 0))         // check cell (x+dx, y+dy) ...```
kind regards,

Jos
• 04-01-2013, 09:02 AM
romero4742
Re: Checking surrounding indexes of an index in a 2d array
Awesome it will take some recursion away :D thanks a lot
• 04-01-2013, 09:11 AM
JosAH
Re: Checking surrounding indexes of an index in a 2d array
Quote:

Originally Posted by romero4742
Awesome it will take some recursion away :D thanks a lot

You're welcome and indeed, no recursion is needed here but don't be afraid of recursion; most of the times recursion is your friend and it allows for very elegant solutions of the problem.

kind regards,

Jos