Counting lattice points inside a triangle

不打扰是莪最后的温柔 提交于 2019-12-05 14:06:29

This problem can and should be solved using Pick's theorem. Read the article to have a full understanding on how it works and it will work for any polygon you can think of. So, "Pick says" that if you want to compute the area of a polygon you have the formula area = noOfInsidePoints + noOfBoundaryPoints /2 - 1. To compute the area of any polygon you can use the following code, where pc is an array of structures representing the vertices of the polygon.

float computeArea()
{
    float area = 0;
    for(int i=1;i<=n;++i) // n is the total number of vertices
        area += (pc[i].x*pc[i+1].y - pc[i+1].x*pc[i].y );
    if(area < 0)
        area *= (-1);
}

Having the area computed, we have to count the number of point from all of the polygon edges. This can be done using the following:

int getBoundaryPoints()
{
    long left=0, right=0;
    int noPoints = 0;
    for(int i=1;i<=n;++i)
    {
        st = abst( pc[i].x - pc[i+1].x );
        right = abs( pc[i].y - pc[i+1].y );
        if(right == 0)
            right = left;
        if(left == 0)
            left = right;
        noPoints += gcd(left, right) +1;
    }
}

Having this computed too, we can find the number of point inside

noPointsInside = (computeArea() - (getBoundaryPoints() - n)) / 2 + 1;

Final time complexity: O(N) Final memory complexity: O(N)

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