Skip to content

Commit d43cf68

Browse files
Merge pull request #286 from asifsadek/master
graham_scan
2 parents fc35b09 + 71ed50e commit d43cf68

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

graham_scan.cpp

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
2+
3+
#include <iostream>
4+
#include <algorithm>
5+
#include <vector>
6+
using namespace std;
7+
8+
struct point
9+
{
10+
double x, y;
11+
point(double x, double y) : x(x), y(y)
12+
{
13+
}
14+
point()
15+
{
16+
}
17+
};
18+
19+
// custom compare for sorting points
20+
bool cmp(point a, point b)
21+
{
22+
return a.x < b.x || (a.x == b.x && a.y < b.y);
23+
}
24+
25+
// check clockwise orientation of points
26+
bool cw(point a, point b, point c)
27+
{
28+
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < 0;
29+
}
30+
31+
// check counter-clockwise orientation of points
32+
bool ccw(point a, point b, point c)
33+
{
34+
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0;
35+
}
36+
37+
// graham scan with Andrew improvements
38+
void convex_hull(vector<point> &points)
39+
{
40+
if (points.size() == 1)
41+
return;
42+
sort(points.begin(), points.end(), &cmp);
43+
point p1 = points[0], p2 = points.back();
44+
vector<point> up, down;
45+
up.push_back(p1);
46+
down.push_back(p1);
47+
for (size_t i = 1; i < points.size(); ++i)
48+
{
49+
if (i == points.size() - 1 || cw(p1, points[i], p2))
50+
{
51+
while (up.size() >= 2 && !cw(up[up.size() - 2], up[up.size() - 1], points[i]))
52+
up.pop_back();
53+
up.push_back(points[i]);
54+
}
55+
if (i == points.size() - 1 || ccw(p1, points[i], p2))
56+
{
57+
while (down.size() >= 2 &&
58+
!ccw(down[down.size() - 2], down[down.size() - 1], points[i]))
59+
down.pop_back();
60+
down.push_back(points[i]);
61+
}
62+
}
63+
cout << "Convex hull is:" << endl;
64+
for (size_t i = 0; i < up.size(); ++i)
65+
cout << "x: " << up[i].x << " y: " << up[i].y << endl;
66+
for (int i = down.size() - 2; i > 0; --i)
67+
cout << "x: " << down[i].x << " y: " << down[i].y << endl;
68+
}
69+
70+
int main()
71+
{
72+
int n;
73+
cout << "Enter number of points followed by points" << endl;
74+
cin >> n;
75+
vector<point> points(n);
76+
for (int i = 0; i < n; i++)
77+
cin >> points[i].x >> points[i].y;
78+
convex_hull(points);
79+
return 0;
80+
}

0 commit comments

Comments
 (0)