




Sponsored
Sponsored
The Monotone Chain Algorithm is an efficient algorithm for finding the convex hull of a set of 2D points. It constructs the hull in O(n log n) time. The idea is to sort the points, then construct the lower and upper hulls in O(n) time each. Points are rejected if they don't form a 'left turn', which can be determined using cross product.
Time complexity is O(n log n) due to sorting. Space complexity is O(n) for storing the hull points.
1using System;
2using System.Collections.Generic;
3
4class Point : IComparable<Point> {
5    public int x, y;
6    public Point(int x, int y) {
7        this.x = x;
8        this.y = y;
9    }
10    public int CompareTo(Point p) {
11        return x == p.x ? y - p.y : x - p.x;
12    }
13}
14
15class Program {
16    static int Cross(Point O, Point A, Point B) {
17        return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
18    }
19
20    static List<Point> ConvexHull(Point[] points) {
21        Array.Sort(points);
22        List<Point> hull = new List<Point>();
23
24        for (int i = 0; i < points.Length; i++) {
25            while (hull.Count >= 2 && Cross(hull[hull.Count - 2], hull[hull.Count - 1], points[i]) <= 0)
26                hull.RemoveAt(hull.Count - 1);
27            hull.Add(points[i]);
28        }
29
30        for (int i = points.Length - 2, t = hull.Count + 1; i >= 0; i--) {
31            while (hull.Count >= t && Cross(hull[hull.Count - 2], hull[hull.Count - 1], points[i]) <= 0)
32                hull.RemoveAt(hull.Count - 1);
33            hull.Add(points[i]);
34        }
35
36        hull.RemoveAt(hull.Count - 1);
37        return hull;
38    }
39
40    static void Main(string[] args) {
41        Point[] trees = { new Point(1, 1), new Point(2, 2), new Point(2, 0), new Point(2, 4), new Point(3, 3), new Point(4, 2) };
42        List<Point> result = ConvexHull(trees);
43        Console.WriteLine("Convex Hull:");
44        foreach (var p in result) 
45            Console.WriteLine($"({p.x}, {p.y})");
46    }
47}The C# solution implements sorting of points and subsequent hull construction using Monotone Chain. Use List operations to maintain the hull efficiently while ensuring valid turns with cross product checks.
The Gift Wrapping Algorithm, also known as Jarvis March, is another method to find the convex hull. It builds the hull one vertex at a time, looking for the line tangent to the current edge and a point in the set of all remaining points. It's less efficient than Monotone Chain, operating in O(nh) time complexity, where h is the number of hull vertices.
Time complexity is O(nh) where n is the number of points and h is the number of points on the hull. Space complexity is O(h) for the hull array.
1
This Python code implements the Gift Wrapping algorithm to construct the convex hull. It chooses leftmost points initially then iteratively selects the next most counterclockwise point using the orientation metric.