C# – the quickest way to find the shortest cartesian distance between two polygons


I have 1 red polygon say and 50 randomly placed blue polygons – they are situated in geographical 2D space. What is the quickest/speediest algorithim to find the the shortest distance between a red polygon and its nearest blue polygon?

Bear in mind that it is not a simple case of taking the points that make up the vertices of the polygon as values to test for distance as they may not necessarily be the closest points.

So in the end – the answer should give back the closest blue polygon to the singular red one.

This is harder than it sounds!

Best Solution

I doubt there is better solution than calculating the distance between the red one and every blue one and sorting these by length.

Regarding sorting, usually QuickSort is hard to beat in performance (an optimized one, that cuts off recursion if size goes below 7 items and switches to something like InsertionSort, maybe ShellSort).

Thus I guess the question is how to quickly calculate the distance between two polygons, after all you need to make this computation 50 times.

The following approach will work for 3D as well, but is probably not the fastest one:

Minimum Polygon Distance in 2D Space

The question is, are you willing to trade accuracy for speed? E.g. you can pack all polygons into bounding boxes, where the sides of the boxes are parallel to the coordinate system axes. 3D games use this approach pretty often. Therefor you need to find the maximum and minimum values for every coordinate (x, y, z) to construct the virtual bounding box. Calculating the distances of these bounding boxes is then a pretty trivial task.

Here's an example image of more advanced bounding boxes, that are not parallel to the coordinate system axes:

Oriented Bounding Boxes - OBB

However, this makes the distance calculation less trivial. It is used for collision detection, as you don't need to know the distance for that, you only need to know if one edge of one bounding box lies within another bounding box.

The following image shows an axes aligned bounding box:

Axes Aligned Bounding Box - AABB

OOBs are more accurate, AABBs are faster. Maybe you'd like to read this article:

Advanced Collision Detection Techniques

This is always assuming, that you are willing to trade precision for speed. If precision is more important than speed, you may need a more advanced technique.