Say you have a 2D grid with each spot on the grid having x number of objects (with x >=0). I am having trouble thinking of a clean algorithm so that when a user specifies a coordinate, the algorithm finds the closest coordinate (including the one specified) with an object on it.
For simplicity’s sake, we’ll assume that if 2 coordinates are the same distance away the first one will be returned (or if your algorithm doesn’t work this way then the last one, doesn’t matter).
Edit: A coordinate that is 1 away must be either 1 up, down, left or right. Coordinates that are away diagonally are 2.
As a side note, what is a great, free, online reference for algorithms?
Update
With new information:
This algorithm would work. The algorithm searches outwards in a spiral kinda way testing each point in each ‘ring’ started from the inside.
Note that it does not handle out of bounds situations. So you should change this to fit your needs.
Old version
Assuming that in your 2D grid the distance between (0, 0) and (1, 0) is the same as (0, 0) and (1, 1). This algorithm would work. The algorithm searches outwards in a spiral kinda way testing each point in each ‘ring’ started from the inside.
Note that it does not handle out of bounds situations. So you should change this to fit your needs.