BLOG.CSHARPHELPER.COM: Find the convex hull of a set of points in C#
Find the convex hull of a set of points in C#
A convex hull is a smallest convex polygon that surrounds a set of points. If you imagine the points as pegs sticking up in a board, then you can think of a convex hull as the shape made by a rubber band wrapped around them.
This program demonstrates several useful techniques for finding convex hulls.
It uses an AngleValue function to order the points. It uses the numeric value dy / (dy + dx) to order the angle from one point to another with respect to the horizontal. This number is not the angle itself, but it has the property that AngleValue(x) < AngleValue(y) if Angle(x) < Angle(y).
The program starts with a point guaranteed to be on the convex hull. For example, the point with the smallest Y coordinate. Then it begins sweeping around to find the point with the smallest AngleValue. It adds that point to the hull and repeats the sweep from the new point starting with the sweep angle it used in the last test. This process continues until the program finds the start point again.
The program also culls some points out to make finding the convex hull faster. To do this, it finds the points that most closely represent the set's upper left, upper right, lower left, and lower right corners. It finds the largest rectangle parallel to the X and Y axes that fits within the quadrilateral defined by those points. This rectangle is guaranteed to lie within the convex hull so any point that lies entirely within the rectangle cannot be on the convex hull. That lets the program remove those points from consideration.
To use the program, click several times to select points. Each time you select a point, the program draws the points, highlights those that are culled, draws the culling quadrilateral and rectangle, and draws the convex hull.
Download the example program to see how the code works.
Comments