-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Jarvis March_Convex Hulls_C++
- Loading branch information
1 parent
af89662
commit f165e46
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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; | ||
} |