Algorithm for finding nearest object on 2D grid

前端 未结 4 1454
感情败类
感情败类 2020-12-23 21:27

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 speci

4条回答
  •  滥情空心
    2020-12-23 22:09

    The following simple solution assumes that you can afford storing extra information per grid cell, and that the time cost of adding new objects to the grid is allowed to be relatively high.

    The idea is that every cell holds a reference to the closest occupied cell, thus allowing O(1) query time. Whenever an object is added to position (i,j), perform a scan of the surrounding cells, covering rings of increasing size. For each cell being scanned, evaluate its current closest occupied cell reference, and replace it if necessary. The process ends when the last ring being scanned isn't modified at all. In the worst case the process scans all grid cells, but eventually it becomes better when the grid becomes dense enough.

    This solution is simple to implement, may have a significant space overhead (depending on how your grid is organized in memory), but provides optimal query time.

提交回复
热议问题