Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most efficient way to check neighbouring grid

Suppose I have a large square grid represented by a two-dimensional array A of size NxN, and a point is assigned to one of the grid by on its coordinates. Each grid is surrounded by eight neighbouring grids (think of the number pad in the keyboard, no.5 is surrounded by 1,2,3,4,6,7,8,9).

Now for each of the neighbouring grids I will do something for it, but some of the elements in the array may not have eight neighbouring grids. If it is on one of the for boarders then it only has five neighbours (like no.2 is surrounded by only 1,3,4,5,6), and if it on one of the four corners then it is surrounded by only three neighbours. Given an element of the array A, how to check its neighbours in the most efficient way? I can just set up many if statements to see if its array index is larger than 0 or smaller than N-1, but how to group (nest) those if statements so that the least number of steps is required?

thanks

like image 760
Physicist Avatar asked Feb 09 '23 02:02

Physicist


1 Answers

If you don't want each element to check few conditions you can use a for loop i=1,j=1; i<N-1 && j<N-1; i++,j++ for the "safe" elements.

Then use a loop to iterate over each line like so j=1;j<N-1;j++ {check array[0][j] and array[N-1][j] and the same for i.

Now, you only need to check the corners.

In this way, no element checks more conditions then it must.

like image 98
CIsForCookies Avatar answered Feb 20 '23 05:02

CIsForCookies