If you have a list of objects
If you had all the positions of all the objects in a list, this would be a lot easier as you wouldn't need to search all the empty squares and could perform 2D distance calculations to determine the one closest to you. Loop through your list of objects and calculate the distance as follows:
Define your two points. Point 1 at (x1, y1) and Point 2 at (x2, y2).
xd = x2-x1
yd = y2-y1
Distance = SquareRoot(xd*xd + yd*yd)
Then simply pick the one with the shortest distance.
If you only have a 2D array
If however the problem as described assumes a 2D array where the locations of the objects cannot be listed without first searching for all of them, then you are going to have to do a spiral loop.
Searching for 'Spiral Search Method' comes up with a few interesting links. Here is some code that does a spiral loop around an array, however this doesn't work from an arbitrary point and spiral outwards, but should give you some good ideas about how to achieve what you want.
Here is a similar question about filling values in spiral order in a 2D array.
Anyway, here is how I would tackle the problem:
Given point P
, create a vector pair that specifies an area around P
.
So if P = 4,4
Then your vector pair would be 3,3|5,5
Loop each value in those bounds.
for x = 3 to 5
for y = 3 to 5
check(x,y)
next
next
If a value is found, exit. If not, increase the bounds by one again. So in this case we would go to 2,2|6,6
When looping to check the values, ensure we haven't gone into any negative indexes, and also ensure we haven't exceeded the size of the array.
Also if you extend the bounds n times, you only need to loop the outer boundary values, you do not need to recheck inner values.
Which method is faster?
It all depends on:
- The density of your array
- Distribution technique
- Number of objects
Density of Array
If you have a 500x500 array with 2 objects in it, then looping the list will always outperform doing a spiral
Distribution technique
If there are patterns of distribution (IE the objects tend to cluster around one another) then a spiral may perform faster.
Number of objects
A spiral will probably perform faster if there are a million objects, as the list technique requires you to check and calculate every distance.
You should be able to calculate the fastest solution by working out the probability of a space being filled, compared to the fact that the list solution has to check every object every time.
However, with the list technique, you may be able to do some smart sorting to improve performance. It's probably worth looking into.