Point in polygon

南笙酒味 提交于 2019-12-02 21:57:40

问题


I'm trying to do some SPOJ problem it's https://www.spoj.pl/problems/FSHEEP/

We have to find out if point is inside the polygon. As we see it's not convex polygon ( image from problem ).

I was trying to solve it in O(n*m) time with Ray Casting algorithm described on wikipedia or any other site.

But how to solve it in O(n log m ) ? So in other words how to check if point is in polygon in logarithmic time ?

Cheers


回答1:


Since this is a homework-esque problem, I'll give you homework-esque help.

Rule of thumb: Whenever you see log n, you should think "binary-something" (search, tree, etc). When you see n log n, you should think "sort." You'll be surprised how often that works. Can you sort the vertices and binary search on them within your big-O constraints?

UPDATE:

I didn't want to spoil your fun: You are actually given the polygon vertices in sorted order, so the important sorting was done for you. You don't need to make an interval in angle-space, use the indexes of the sorted vertex array as your interval.

Cast your ray out from the farmer to the vertex. If it is clockwise, binary search clockwise. If it is anti-clockwise, binary search that direction. The two vertices and the farmer form a bounding triangle. Is the sheep in the bounding triangle?

Crazy lazy pseudocode:

if vertex[m] and vertex[0] trivially bound the sheep
  l=m, r=0
else
  l=0, r=m
  while (r-l > 1)
    middle = (r-l)/2
    if vertex[l] and vertex[middle] bound sheep
       r = middle
       continue
    else if vertex[middle] and vertex[r] bound sheep
       l = middle
       continue
    else some_jerk_gave_you_a_sheep_on_a_ray

check vertex[l],vertex[r],farmer triangle

Binary search is O(log m). The triangle check is O(1). Iterating over n sheep gives you O(n)*O(log m)*O(1) = O(n log m).



来源:https://stackoverflow.com/questions/6100931/point-in-polygon

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