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

1. Member
Join Date
Mar 2012
Posts
27
Rep Power
0

## 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

Java 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);
}```

2. ## 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

3. Member
Join Date
Mar 2012
Posts
27
Rep Power
0

## 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

4. ## Re: Checking surrounding indexes of an index in a 2d array

For two dimensional indexes it's easy:

Java 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

5. Member
Join Date
Mar 2012
Posts
27
Rep Power
0

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

Awesome it will take some recursion away :D thanks a lot

6. ## Re: Checking surrounding indexes of an index in a 2d array

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