16

For a polygon defined as a sequence of (x,y) points, how can I detect whether it is complex or not? A complex polygon has intersections with itself, as shown:

example complex polygon image

Is there a better solution than checking every pair which would have a time complexity of O(N2)?

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • Well, if polygon is entered by user with gmaps, then you're not likely to have more than 100 vertexes. In this case, I would go with simple solution first and see if it's enough. – Nikita Rybak Oct 23 '10 at 00:00
  • @Nikita, the question may have been misleading in that regard. The user can also edit an existing polygon with thousands of vertices. Regardless, I'm still interested to know the best approach for this. – Drew Noakes Oct 23 '10 at 00:03

3 Answers3

13

There are sweep methods which can determine this much faster than a brute force approach. In addition, they can be used to break a non-simple polygon into multiple simple polygons.

For details, see this article, in particular, this code to test for a simple polygon.

Andy Baker
  • 21,158
  • 12
  • 58
  • 71
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    The code link is http://geomalgorithms.com/a09-_intersect-3.html#simple_Polygon() the auto-escaped version from markdown doesn't work. – Ryan Ahearn Jun 26 '13 at 14:01
  • 2
    Links are broken. This answer doesn't have any information other than "there exists an algorithm that does this." This is why it's important for answers to be self-contained. :( – Cris Luengo Feb 18 '22 at 16:13
5

See Bentley Ottmann Algorithm for a sweep based O((N + I)log N) method for this. Where N is the number of line segments and I is number of intersection points.

Amit Prakash
  • 1,171
  • 10
  • 19
1

In fact, this can be done in linear time use Chazelle's triangulation algorithm. It either triangulates the polygon or find out the polygon is not simple.

Chao Xu
  • 2,156
  • 2
  • 22
  • 31