Sorting polygon's points

房东的猫 提交于 2019-12-18 20:02:39

问题


I have a convex polygon ABCDE... (it can have any number of points). I need to sort all its vertexes so none of the edges will intersect.
example:

A _____ B
  \   /
   \ /
    X
   / \
  /___\
C       D

That polygon in ABCD order has intersecting edges. however in ABDC order:

A _____ B
  |   |
  |   |
  |   |
  |   |
  |___|
C       D

None of the edges intersect so ABDC is the expected output.

How can I do this?


回答1:


Assuming your points are all on the convex hull of your polygon, you can use the following:

  1. Pick the two extreme points with the min and max X value, (call them Xmin and Xmax) and draw the line between them. In the case where you have multiple points with the same X value at the extremes, pick Xmin with the minimum Y value and Xmax with the maximum Y value.
  2. Split the list of points into two sub lists where all of the points below the line connecting Xmin and Xmax are in one list and all those above that line are in another. Include Xmin in the first list and Xmax in the second.
  3. Sort the first list in ascending order of X value. If you have multiple points with the same X value, sort them in ascending Y value. This should only happen for points with the same X component as Xmax since the polygon is convex.
  4. Sort the second list in descending order of X value. Again, sort in descending Y value in the event of multiple points with the same X value (which should only happen for points with X component Xmin.
  5. Append the two lists together (it doesn't matter which is first).



回答2:


choose two points on the polygon. the midpoint of the line will be contained within that polygon. Let that point be M.

Then, sort the points based on the angle based from M (along the X axis), breaking degeneracy based on distance from M. Iterating in that order ensures that no two edges will intersect.



来源:https://stackoverflow.com/questions/7369710/sorting-polygons-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!