preferred way of finding neighbours in a 2d array

Hi, I am working on a OOP project and I have to see if any of my neighbouring 8 cells contains a specific value or not. Now I know how to find it but don't know which way will be more attractive to my employers.
The easiest and probably fastest way to do it is by hard coding it and checking for bounds. But I don't know if using other way is much preferred or what.
Thanks.

(hard coded)
array[i-1][j-1]
array[i-1][j]
array[i-1][j+1]
array[i][j-1]
array[i][j+1]
array[i+1][j-1]
array[i+1][j]
array[i+1][j+1]


(the other way)

for(i=0; i<max.row; i++)
{
   for(j=0; j<max.col; j++)
   {
     //check for left bound
     if(i>0)
     {
       //check for top bound
        if(y>0)
        {
            //do something
        }
        //check for bottom bound
        if(y<max.col)
        {
            //do something
         }
      }
     //check for right bound
     if(x<max.row)
     {
         //check for top bound
         if(y>0)
         {
            //do something
         }
         //check for bottom bound
         if(y<max.col)
         {
            //do something   
         }
     }
  }
Last edited on
closed account (D80DSL3A)
We would like to automate the process of bound checking and indexing to the 8 neighboring sites.
This function is quite useful for automating bounds checking:
1
2
3
4
5
6
bool inField( int r, int c )
{
  if( r < 0 || r >= rows ) return false;
  if( c < 0 || c >= cols ) return false;
    return true;
}


and these arrays defining the 8 offsets to neighbors are handy too:
1
2
const int y[] = { -1, -1, -1,  1, 1, 1,  0, 0 };// 8 shifts to neighbors
const int x[] = { -1,  0,  1, -1, 0, 1, -1, 1 };// used in functions 


Then the cumbersome task may be accomplished as:
1
2
3
4
        
for(int i=0; i<8; ++i)// visit the 8 spaces around it
   if( inField( r+y[i], c+x[i] ) )
          // do something 


edit: I realized I answered the wrong question the 1st time.
Last edited on
Sometimes you can avoid the bounds check altogether. If you have to store an NxN array, then store it in an (N+2)x(N+2) array where boundaries of this array are empty and the data is in indexes (1,1) to (N,N).

This technique works for some problems, such as a game board where you need to know if a piece has neighbors.

And of course, it's trading data space for code space and run time.
Topic archived. No new replies allowed.