Finding if Path2D self-intersects

前端 未结 2 1881
无人共我
无人共我 2021-02-14 08:18

I need to find if Path2D intersects itself. For now, I do it by simply extracting an array of lines from path, and finding if any of these intersect. But it has O(n^2) complexit

2条回答
  •  滥情空心
    2021-02-14 09:00

    You can do this faster using the sweep-line algorithm: http://en.wikipedia.org/wiki/Sweep_line_algorithm

    Pseudocode:

    Each line has a start point and an end point. Say that `start_x` <= `end_x` for all the lines.
    Create an empty bucket of lines.
    Sort all the points by their x coordinates, and then iterate through the sorted list.
    If the current point is a start point, test its line against all the lines in the bucket, and then add its line to the 
    bucket.
    if the current point is an end point, remove its line from the bucket.
    

    The worst case is still O(N^2), but the average case is O(NlogN)

提交回复
热议问题