-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jarvis March_Convex Hulls_C++
75 lines (62 loc) · 1.49 KB
/
Jarvis March_Convex Hulls_C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Jarvis March Convex Hull
#include <iostream>
using namespace std;
#define INF 10000
struct Point
{
int x;
int y;
};
int orientation(Point p1, Point p2, Point p3)
{
int val = (p2.y - p1.y) * (p3.x - p2.x) - (p2.x - p1.x) * (p3.y - p2.y);
if (val == 0)
return 0; // colinear
else if(val > 0)
return 1; //clockwise
else
return 2; // counterclock wise
}
// Prints convex hull of a set of n points.
void convexHull(Point points[], int n)
{
int i;
if (n < 3)
return;
// Initialize Result
int next[n];
for (i = 0; i < n; i++)
next[i] = -1;
// Find the leftmost point
int l = 0;
for (i = 1; i < n; i++)
if (points[i].x < points[l].x)
l = i;
int p = l, search_q;
do
{
search_q = (p + 1) % n;
for (i = 0; i < n; i++)
if (orientation(points[p], points[i], points[search_q]) == 2)
search_q = i;
next[p] = search_q;
p = search_q;
}
while (p != l);
// Print Result
for (i = 0; i < n; i++)
{
if (next[i] != -1)
cout << "(" << points[i].x << ", " << points[i].y << ")"<<endl;
}
}
// Driver program
int main()
{
Point points[] = { { 0, 3 }, { 2, 2 }, { 1, 1 }, { 2, 1 }, { 3, 0 },
{ 0, 0 }, { 3, 3 } };
cout << "The points in the convex hull are: "<<endl;
int n= sizeof(points) / sizeof(points[0]);
convexHull(points, n);
return 0;
}