![]() |
VOOZH | about |
Given a polygon, your task is to calculate the number of lattice points inside the polygon and on its boundary. A lattice point is a point whose coordinates are integers.
The polygon consists of n vertices (x1,y1),(x2,y2),....,(xn,yn). The vertices (xi,yi) and (xi+1,yi+1) are adjacent for i=1,2,....,n-1, and the vertices (x1,y1) and (xn,yn) are also adjacent.
Example:
Input: n = 4, vertices = {{1, 1}, {5, 3}, {3, 5}, {1, 4}}
Output: 6 8Input: n = 4, vertices = {{2, 4}, {3, 2}, {1, 3}, {2, 4}}
Output: 1 3
Approach:
The idea is to use calculate the area of the polygon using the shoelace formula and Pick's theorem, which states that the number of lattice points inside a polygon is given by the following formula:
interior = (area + 2 - boundary) / 2where:
- interior is the number of lattice points inside the polygon
- area is the area of the polygon
- boundary is the number of lattice points on the boundary of the polygon
Steps-by-step approach:
Note: why __gcd(abs(x[i + 1] - x[i]), abs(y[i + 1] - y[i])) function is used to calculate the number of boundary points on a diagonal edge of the polygon !!
- When two points form a diagonal edge, the number of boundary points on this edge is the number of grid points that the line segment between these two points passes through.
- To calculate this, we use the greatest common divisor (gcd) of the absolute differences in their x and y coordinates. The gcd of two numbers is the largest number that divides both of them without leaving a remainder. In this context, it represents the number of grid points that the diagonal line segment intersects.
- For example, consider two points (3, 3) and (6, 6). The line segment between these points is a diagonal line that passes through (4, 4) and (5, 5). So, there are 3 boundary points on this edge: (3, 3), (4, 4), and (5, 5). The absolute differences in the x and y coordinates are 3 and 3, respectively, and their gcd is 3, which is the correct number of boundary points.
- So, the __gcd function is used to correctly calculate the number of boundary points on a diagonal edge. This ensures that the total number of boundary points on the polygon is accurate.
Below are the implementation of the above approach:
6 8
Time complexity: O(nlog(n)), where n is the number of vertices in the polygon, log(n) due to gcd function.
Auxiliary Space: O(n)