Count Lattice Points Inside a Circle Problem
Description
LeetCode Problem 2249.
Given a 2D integer array circles where circles[i] = [x_i, y_i, r_i] represents the center (x_i, y_i) and radius r_i of the i^th circle drawn on a grid, return the number of lattice points that are present inside at least one circle.
Note:
- A lattice point is a point with integer coordinates.
- Points that lie on the circumference of a circle are also considered to be inside it.
Example 1:

Input: circles = [[2,2,1]]
Output: 5
Explanation:
The figure above shows the given circle.
The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.
Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.
Hence, the number of lattice points present inside at least one circle is 5.
Example 2:

Input: circles = [[2,2,2],[3,4,1]]
Output: 16
Explanation:
The figure above shows the given circles.
There are exactly 16 lattice points which are present inside at least one circle.
Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).
Constraints:
1 <= circles.length <= 200circles[i].length == 31 <= x_i, y_i <= 1001 <= r_i <= min(x_i, y_i)
Solution
Approach: Check Every Lattice Point
All centers and radii are at most 100, so every circle lies inside the box from (0, 0) to (max(x + r), max(y + r)), which has at most about 200 by 200 points.
For each lattice point (i, j) in that box, test the circles one by one: the point is inside a circle when (i - x)^2 + (j - y)^2 <= r^2. As soon as one circle contains it, count the point and stop checking further circles, so a point covered by several circles is counted once.
Complexity: O(X * Y * n) time, where X and Y are the box dimensions and n is the number of circles; O(1) extra space.
class Solution:
def countLatticePoints(self, circles: List[List[int]]) -> int:
ans = 0
mx = max(x + r for x, _, r in circles)
my = max(y + r for _, y, r in circles)
for i in range(mx + 1):
for j in range(my + 1):
for x, y, r in circles:
dx, dy = i - x, j - y
if dx * dx + dy * dy <= r * r:
ans += 1
break
return ans