Minimum Sensors to Cover Grid Problem
Description
LeetCode Problem 3648.
You are given n × m grid and an integer k.
A sensor placed on cell (r, c) covers all cells whose Chebyshev distance from (r, c) is at most k.
The Chebyshev distance between two cells (r_1, c_1) and (r_2, c_2) is max(|r_1 − r_2|,|c_1 − c_2|).
Your task is to return the minimum number of sensors required to cover every cell of the grid.
Example 1:
Input: n = 5, m = 5, k = 1
Output: 4
Explanation:
Placing sensors at positions (0, 3), (1, 0), (3, 3), and (4, 1) ensures every cell in the grid is covered. Thus, the answer is 4.
Example 2:
Input: n = 2, m = 2, k = 2
Output: 1
Explanation:
With k = 2, a single sensor can cover the entire 2 * 2 grid regardless of its position. Thus, the answer is 1.
Constraints:
1 <= n <= 10^31 <= m <= 10^30 <= k <= 10^3
Solution
Approach: Tile with Squares
A sensor covers every cell within Chebyshev distance k, which is a square of side d = 2k + 1 centered on it (cut off at the grid border). Such a square contains at most d rows and d columns, so cutting the grid into blocks of d by d cells, one sensor in the middle of each block covers it, and no sensor can do better than one block's worth of cells in a row or column direction.
Down a column we need ceil(n / d) blocks and along a row ceil(m / d) blocks, so the answer is ceil(n / d) * ceil(m / d). For k = 0 this is n * m.
Complexity: O(1) time and O(1) extra space.
class Solution:
def minSensors(self, n: int, m: int, k: int) -> int:
d = 2 * k + 1
return ((n + d - 1) // d) * ((m + d - 1) // d)