📜  凸包|套装2(Graham Scan)

📅  最后修改于: 2021-05-06 23:48:21             🧑  作者: Mango

给定平面上的一组点。该集合的凸包是包含其所有点的最小凸多边形。

强烈建议您先阅读以下文章。
如何检查两个给定的线段是否相交?
我们已经讨论了Jarvis的凸包算法。 Jarvis算法的最坏情况下时间复杂度为O(n ^ 2)。使用Graham的扫描算法,我们可以在O(nLogn)时间中找到凸包。以下是格雷厄姆的算法
令points [0..n-1]为输入数组。
1)通过比较所有点的y坐标找到最底端的点。如果有两个具有相同y值的点,则考虑具有较小x坐标值的点。设最低点为P0。将P0放在输出船体的第一个位置。
2)考虑剩余的n-1个点,并按极角围绕点[0]沿逆时针顺序对其进行排序。如果两个点的极角相同,则将最近的点放在第一位。
3排序后,检查两个或多个点是否具有相同的角度。如果另外两个点具有相同的角度,则移除所有相同的角度点,但最远离P0的点除外。令新数组的大小为m。
4)如果m小于3,则返回(无法使用凸包)
5)创建一个空堆栈’S’并将point [0],points [1]和points [2]推到S。
6)逐一处理剩余的m-3点。对每个点“ points [i]”进行追踪
4.1)当后面的3个点的方向不是逆时针方向(或者它们没有向左转)时,请从堆栈中移除点。
a)堆栈顶部附近的点
b)指向堆栈顶部
c)点[i]
4.2)将点[i]推到S
5)打印S的内容
上面的算法可以分为两个阶段。
第1阶段(排序点):我们首先找到最低点。想法是对点进行预处理,然后将它们相对于最底端的点进行排序。对点进行排序后,它们将形成一条简单的闭合路径(请参见下图)。

排序标准应该是什么?由于三角函数不容易评估,因此实际角度的计算将效率很低。这个想法是使用方向来比较角度而不实际计算角度(请参见下面的compare()函数)
第2阶段(接受点或拒绝点):有了闭合路径后,下一步就是遍历该路径并删除该路径上的凹点。如何确定要删除的点和要保留的点?同样,方向在这里有帮助。排序数组中的前两点始终是凸包的一部分。对于其余的点,我们跟踪最近的三个点,并找到它们形成的角度。令这三个点为prev(p),curr(c)和next(n)。如果这些点的方向(以相同顺序考虑)不是逆时针方向,则将其丢弃,否则将其保留。下图显示了此阶段的逐步过程。

以下是上述算法的C++实现。

CPP
// A C++ program to find convex hull of a set of points. Refer
// https://www.geeksforgeeks.org/orientation-3-ordered-points/
// for explanation of orientation()
#include 
#include 
#include 
using namespace std;
 
struct Point
{
    int x, y;
};
 
// A global point needed for  sorting points with reference
// to  the first point Used in compare function of qsort()
Point p0;
 
// A utility function to find next to top in a stack
Point nextToTop(stack &S)
{
    Point p = S.top();
    S.pop();
    Point res = S.top();
    S.push(p);
    return res;
}
 
// A utility function to swap two points
void swap(Point &p1, Point &p2)
{
    Point temp = p1;
    p1 = p2;
    p2 = temp;
}
 
// A utility function to return square of distance
// between p1 and p2
int distSq(Point p1, Point p2)
{
    return (p1.x - p2.x)*(p1.x - p2.x) +
          (p1.y - p2.y)*(p1.y - p2.y);
}
 
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
    int val = (q.y - p.y) * (r.x - q.x) -
              (q.x - p.x) * (r.y - q.y);
 
    if (val == 0) return 0;  // colinear
    return (val > 0)? 1: 2; // clock or counterclock wise
}
 
// A function used by library function qsort() to sort an array of
// points with respect to the first point
int compare(const void *vp1, const void *vp2)
{
   Point *p1 = (Point *)vp1;
   Point *p2 = (Point *)vp2;
 
   // Find orientation
   int o = orientation(p0, *p1, *p2);
   if (o == 0)
     return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;
 
   return (o == 2)? -1: 1;
}
 
// Prints convex hull of a set of n points.
void convexHull(Point points[], int n)
{
   // Find the bottommost point
   int ymin = points[0].y, min = 0;
   for (int i = 1; i < n; i++)
   {
     int y = points[i].y;
 
     // Pick the bottom-most or chose the left
     // most point in case of tie
     if ((y < ymin) || (ymin == y &&
         points[i].x < points[min].x))
        ymin = points[i].y, min = i;
   }
 
   // Place the bottom-most point at first position
   swap(points[0], points[min]);
 
   // Sort n-1 points with respect to the first point.
   // A point p1 comes before p2 in sorted output if p2
   // has larger polar angle (in counterclockwise
   // direction) than p1
   p0 = points[0];
   qsort(&points[1], n-1, sizeof(Point), compare);
 
   // If two or more points make same angle with p0,
   // Remove all but the one that is farthest from p0
   // Remember that, in above sorting, our criteria was
   // to keep the farthest point at the end when more than
   // one points have same angle.
   int m = 1; // Initialize size of modified array
   for (int i=1; i S;
   S.push(points[0]);
   S.push(points[1]);
   S.push(points[2]);
 
   // Process remaining n-3 points
   for (int i = 3; i < m; i++)
   {
      // Keep removing top while the angle formed by
      // points next-to-top, top, and points[i] makes
      // a non-left turn
      while (S.size()>1 && orientation(nextToTop(S), S.top(), points[i]) != 2)
         S.pop();
      S.push(points[i]);
   }
 
   // Now stack has the output points, print contents of stack
   while (!S.empty())
   {
       Point p = S.top();
       cout << "(" << p.x << ", " << p.y <<")" << endl;
       S.pop();
   }
}
 
// Driver program to test above functions
int main()
{
    Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
                      {0, 0}, {1, 2}, {3, 1}, {3, 3}};
    int n = sizeof(points)/sizeof(points[0]);
    convexHull(points, n);
    return 0;
}


输出:

(0, 3)
(4, 4)
(3, 1)
(0, 0) 

时间复杂度:令n为输入点数。如果我们使用O(nLogn)排序算法,则该算法将花费O(nLogn)时间。
第一步(找到最底点)需要O(n)时间。第二步(排序点)需要O(nLogn)时间。第三步花费O(n)时间。第三步,每个元素最多被推送和弹出一次。因此,假设堆栈操作需要O(1)时间,第六个步骤一步一步地处理O.n。总体复杂度为O(n)+ O(nLogn)+ O(n)+ O(n),即O(nLogn)。