




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.
1
This JavaScript solution uses the Monotone Chain Algorithm. After sorting the points, it builds the lower and upper hulls using stack operations and combines them to form the complete convex hull, taking care of duplicate endpoints.
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.
1using System;
2using System.Collections.Generic;
3
4class Point {
5    public int x, y;
6    public Point(int x, int y) {
7        this.x = x;
8        this.y = y;
9    }
10}
11
12class Program {
13    static int Orientation(Point p, Point q, Point r) {
14        int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
15        return (val == 0) ? 0 : (val > 0 ? 1 : 2);
16    }
17
18    static List<Point> ConvexHull(Point[] points) {
19        if (points.Length < 3) return new List<Point>();
20        List<Point> hull = new List<Point>();
21
22        int leftmost = 0;
23        for (int i = 1; i < points.Length; i++)
24            if (points[i].x < points[leftmost].x)
25                leftmost = i;
26
27        int p = leftmost, q;
28        do {
29            hull.Add(points[p]);
30            q = (p + 1) % points.Length;
31
32            for (int i = 0; i < points.Length; i++)
33                if (Orientation(points[p], points[i], points[q]) == 2)
34                    q = i;
35
36            p = q;
37
38        } while (p != leftmost);
39
40        return hull;
41    }
42
43    static void Main(string[] args) {
44        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) };
45        List<Point> result = ConvexHull(trees);
46        Console.WriteLine("Convex Hull:");
47        foreach (var p in result)
48            Console.WriteLine($"({p.x}, {p.y})");
49    }
50}This C# solution employs the Gift Wrapping strategy by iterating points to fill the hull. It uses a direction check relative to the previous hull point to ensure counterclockwise traversal for subsequent points.