How many integer points within the three points forming a triangle?

后端 未结 13 1296
一个人的身影
一个人的身影 2020-12-12 21:04

Actually this is a classic problem as SO user Victor put it (in another SO question regarding which tasks to ask during an interview).

I couldn\'t do it in an hour

相关标签:
13条回答
  • 2020-12-12 21:53

    Ok I will propose one algorithm, it won't be brilliant, but it will work.

    First, we will need a point in triangle test. I propose to use the "Barycentric Technique" as explained in this excellent post:

    http://www.blackpawn.com/texts/pointinpoly/default.html

    Now to the algorithm:

    1. let (x1,y1) (x2,y2) (x3,y3) be the triangle vertices

    2. let ymin = floor(min(y1,y2,y3)) ymax = ceiling(max(y1,y2,y3)) xmin = floor(min(x1,x2,x3)) ymax = ceiling(max(x1,x2,3))

    3. iterating from xmin to xmax and ymin to ymax you can enumerate all the integer points in the rectangular region that contains the triangle

    4. using the point in triangle test you can test for each point in the enumeration to see if it's on the triangle.

    It's simple, I think it can be programmed in less than half hour.

    0 讨论(0)
提交回复
热议问题