Skip to content

Commit

Permalink
✨ adds algorithm to find lattice points of a polygon
Browse files Browse the repository at this point in the history
  • Loading branch information
iagorrr committed Nov 22, 2023
1 parent 42dd72f commit dc634e4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
33 changes: 33 additions & 0 deletions algorithms/geometry/polygon-lattice-points.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
ll cross(ll x1, ll y1, ll x2, ll y2) {
return x1 * y2 - x2 * y1;
}

ll polygonArea(vector<pll>& pts) {
ll ats = 0;
for (int i = 2; i < len(pts); i++)
ats += cross(pts[i].first - pts[0].first,
pts[i].second - pts[0].second,
pts[i - 1].first - pts[0].first,
pts[i - 1].second - pts[0].second);
return abs(ats / 2ll);
}

ll boundary(vector<pll>& pts) {
ll ats = pts.size();
for (int i = 0; i < len(pts); i++) {
ll deltax =
(pts[i].first - pts[(i + 1) % pts.size()].first);
ll deltay =
(pts[i].second - pts[(i + 1) % pts.size()].second);
ats += abs(__gcd(deltax, deltay)) - 1;
}
return ats;
}

pll latticePoints(vector<pll>& pts) {
ll bounds = boundary(pts);
ll area = polygonArea(pts);
ll inside = area + 1ll - bounds / 2ll;

return {inside, bounds};
}
5 changes: 5 additions & 0 deletions algorithms/geometry/polygon-lattice-points.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
\subsection{Polygon Lattice Points (Pick's Theorem)}

Given a polygon with $N$ points finds the number of lattice points inside and on boundaries.
Time : $O(N)$

0 comments on commit dc634e4

Please sign in to comment.