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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With