Point in Polygon Algorithm in Programming Contests - algorithm

What is the best algorithm to solve point in polygon in programming contests?

Shoot a ray(in arbitrary direction) from the point and check the number of times it has crossed the edges of polygon if it is even then the point is outside the polygon otherwise the point is inside the polygon.
If you need to do it for lots of query points, you can triangulate the polygon (actually triangulate both inside and the region between the polygon the convex containing it) so that you could do ray shooting in O(log n)

if you have a convex polygon you can use this :
http://e-maxx.ru/algo/pt_in_polygon

Related

Is there any algorithm for covering a concave polygon(contains holes) with convex polygons

This can be approached in two ways :
i) by partitioning the given polygon into convex polygons such that there is no
overlap between the convex polygons
ii) by covering the given polygon using convex polygons such that their union
gives the original polygon. In this case there can be overlap between
the convex polygons
Although partitioning covers the entire polygon, number of convex polygons can be reduced by second approach. It is also known that covering a concave polygon(second approach) with minimal number of convex polygons is NP-Hard.
I'm specifically looking for algorithms based on second approach mentioned above,but number of convex polygons may not be minimal.
As already mentioned by MBo and Yves Daoust in the comments to your questions. Polygon decomposition into convex polygons can be done by triangulation (or trapezoidal decomposition). This will result for an n vertex simple polygon P with n-2 (interior) triangles, i.e., is linear in the number of vertices.
Another way to construct a convex decomposition would be to use a generalized motorcycle graph. I would assume there must be a simpler way though!
The main idea is to start a motorcycle m for every reflex vertex r in P. Every motorcycle m drives with a given speed in a given direction and leaves a trace behind. If another motorcycle meets such a trace it crashes, i.e., stops but leaves the trace.
Generalized refers to the embedding in P and that the polygon boundaries function as walls where the motorcycles also crash. Furthermore if two motorcycles meet at the same point we have to start another one, or in this case just continue with one and stop the other. After all motorcycles have crashed there is the graph of the traces which in fact is a convex tessellation of P. There are several papers (one here) on this but implementation would be tough. This results in O(r) convex polygons that cover the interior of P.
I think the easiest way is to go with the triangulation or trapezoidal decomposition. These are well studied and available as implementation in many libraries.
Also mentioned in the comments: Input can be produced that will force O(n) polygons. Just think of a star shaped polygon that has n/2 reflex vertices (interior angle > pi).

Get the polygon created by moving a polygon

I don't know if the process has a specific name. I want to get the polygon which is created by translating a polygon. Is there an algorithm for this. For example:
.
Convex hull works for convex polygons but I want a general solution. Also I would be happy to hear if there is a way to get the polygon created by rotating.
It appears you are looking for the Minkowski sum of your polygon and the line segment describing your movement.
The CGAL library package 2D Minkowski Sums can compute them for instance.
Given the explanation you gave in comments, the straightforward approach is this:
Let v be a vector describing the linear movement
For each edge (p,q) in the polygon
construct quadrilateral (p, q, q+v, p+v)
Compute the union of all the quadrilaterals plus the original polygon
Computing polygon unions is a well-studied problem with efficient algorithms.

calculate intersection area of two triangle

I have been trying to find an algorithm which computes the intersecting area of two triangles but I failed to find any. Can anybody give a clue how to write this algorithm?
I would like something like:
double getAreaOfIntersection(Vector2 p1,Vector2 p2, Vector2 p3,Vector2 p4,Vector2 p5,Vector2 p6 )
where pX represents the 2 triangles.
You could first compute the polygon which describes the intersection area by a clipping algorithm, e.g.:
Sutherland-Hodgman algorithm
Then you would compute the area of the resulting convex polygon, which is rather easy, see, e.g., here:
Area of a Convex Polygon
Determining wether or not a point lies within a given polygon is easy (and even easier for triangles since those are simple polygons). You can use the winding number algorithm (and the crossing number algorithm for simple polygons) which is implemented and well explained here.
Using this you can obtain all the vertices of your intersection polygon:
The vertices pX of a triangle that are contained in the other triangle as well
The points where the two triangles intersect (see intersection of line segments)
You will need to loop over your edges to find all the intersection points, so this should be quick enough as long as you only want to determine intersections of triangles but i would not suggest to try to find intersections of arbitrary polygons this way.

Confusion on Delaunay Triangulation and Largest inscribed circle

I need to find a largest inscribed circle of a convex polygon, I've searched many sites and I get that this can be done by using Delaunay triangulation. I found a thread in CGAL discussion with an algorithm using CGAL:
You can compute this easily with CGAL:
First, compute the Delaunay triangulation of the points.
Then, iterate on all the finite faces of the triangulation.
For each finite face f
compute its circumcenter c
locate c in the triangulation (to speed up things, you can give one
vertex of f as starting hint for the point location)
if the face returned by locate(c,hint) is finite, then the circumcenter
c lies in the convex hull of the points, so, f is a candidate
if f is such a candidate face, compute its squared circumradius
keep only the face with minimum squared circumradius
The CGAL manual (chapter 2D triangulation, together with a few things
from the kernel) shows every basic function to do this.
I was a bit confused with the last part of this algorithm. When I read it what I understand from it is that the minimum circumradius of the triangulation face is the radius for the largest inscibed circle. But from examples of polygon with Delaunay triangulation, it seems that even the smallest circumcircle sometimes cannot fit inside the polygon, so how can this has the same radius as the largest inscribed circle?
Maximum inscribed circle in polygons.
The classical computational-geometry solution to the maximum inscribed circle problem for polygons is to use the generalized Voronoi diagram of the polygon's faces resp. the medial axis of the polygon. This approach works in a more general setting like polygons with holes, see this stackoverflow answer to a similar question.
Convex input.
The convexity of your input polygon, however, gives the problem more structure, which I would like to comment on. Consider the following convex input polygon (black), the Voronoi diagram (blue), and the maximum inscribed circle (green) centered on a Voronoi node.
The classical Voronoi-based solution is to (i) compute the Voronoi diagram and (ii) take the Voronoi node with largest clearance (i.e., distance to its defining faces).
The Voronoi diagram of a polygon with holes (i.e., the set of vertices and edges) can be computed in O(n log n) time, c.f. Fortune's algorithm (1986). Later Chin et alii (1999) gave an O(n) algorithm for the medial axis of a simple polygon.
For convex polygons, however, a time-optimal algorithm for Voronoi diagram that runs in O(n) time was already known in 1989 due to Aggarwal et alii. This algorithm follows basically the following idea: Consider the grey offset curves moving inwards at unit speed. If you project this movement into three-space where the z-axis is time you get a unit-slop roof over the polygon:
This roof model could also be characterized as follows: Put a half-space on each polygon edge at 45° slope with polygon (such that they contain the polygon) and intersect them all. So if you can quickly compute the intersect of half-spaces then you can also quickly compute Voronoi diagrams of convex polygons. Actually, for the maximum inscribed circle problem we do not need to go back to the Voronoi diagram but take the one peak of the roof, which marks the center of the maximum inscribed circle.
Now the half-spaces are dualized to points, and then the intersection of half-spaces corresponds the convex hull of its dual points. Aggarwal et al. now found an O(n) algorithm for the convex hull of points that stem from this setting.
A summary of this construction that leads to a Voronoi diagram algorithm for convex polyhedra in any dimension can be found in a blog article of mine.
Simple & fast implementation. A simpler algorithm to compute the Voronoi diagram is motivated by straight skeletons. For convex polygons the Voronoi diagram and the straight skeleton are the same.
The algorithm behind the straight-skeleton implementation Stalgo basically simulates the evolution of the wavefront structure (the grey offset curves). For convex polygons this reduces to finding the sequence of edges that collapse.
So a simple O(n log n) algorithm could look like this:
Construct a circular list of the polygon edges. Compute the collapse time of each edge during wavefront propagation, and insert this event into a priority queue.
Until the queue is empty: Take out the next edge-collapse event: Remove the edge from the circular structure and update the collapse times of the neighboring edges of the removed edge.
Actually, you can simplify the above algorithm further: You do not need to update edge collapses in the priority queue but simply insert new ones: Since the new collapse time of edges are strictly lower, you always get the right event first and dismiss the others and the queue is not growing larger than 2n. Hence, you do not compromise the O(n log n) time complexity.
For the maximum inscribed circle problem you can simplify the above algorithm even further: The Voronoi node (resp. straight skeleton node) you look for is due to the collapse of the final triangle at the end of the loop over the priority queue.
This algorithm should be quick in practice and only a few lines of code.
The last step can mean to select the minimum face of the triangle. Then rinse and repeat.

a given point lies inside or outside a polygon

I was trying this question and found a solution :
Draw a horizontal line to the right of each point and extend it to infinity
1) Count the number of times the line intersects with polygon edges.
2) A point is inside the polygon if either count of intersections is odd or
point lies on an edge of polygon. If none of the conditions is true, then
point lies outside.
But i think there is a simple solution to this :
for(all sides in same order)
find vector product of the 3 points (given point and end points of each side)
if all products are > or < 0 : point lies inside polygon or on boundary
else outside
isn't my solution better and efficient ?
is there another simpler algorithm than this ?
The proposed algorithm using cross product check only works for convex polygons. For non-convex polygon it is quite easy to find an example where it does not work. Try any of the points c, d or e in the polygon given.
The algorithm you suggest only works for convex polygons & in fact used for calculation of the convex hull but would fail for concave which is again proved by correctness of convex hull algorithm.
Another way to use this algorithm is to divide your polygon into convex polygons and then apply the algorithm on the divided parts to see if the point is inside anyone of them
Polygon triangulation

Resources