Find the number of p-sided squares in a grid with K blacks painted
Given a grid of size H*W with all cells initially white. Given N pairs (i, j) in an array, for each pair, paint cell (i, j) with black colour. The task is to determine how many squares of size p×p of the grid contains exactly K black cells, after N cells being painted.
Input: H = 4, W = 5, N = 8, K = 4, p = 3 arr=[ (3, 1), (3, 2), (3, 4), (4, 4), (1, 5), (2, 3), (1, 1), (1, 4) ] Output: 4 Cells that are being painted are shown in the figure below: Here p = 3. There are six subrectangles of size 3*3. Two of them contain three black cells each, and the remaining four contain four black cells each.
Input: H = 1, W = 1, N = 1, K = 1, p = 1 arr=[ (1, 1) ] Output: 1
- First thing to observe is that one p*p sub-grid will be different from the other if their starting points are different.
- Second thing is that if the cell is painted black, it will contribute to p^2 different p*p sub-grids.
- For example, suppose cell [i, j] is painted black. Then it will contribute additional +1 to all the subgrids having starting point
[i-p+1][j-p+1] to [i, j].
- Since there can be at most N blacks, for each black cell do p*p iterations and update its contribution for each p*p sub-grids.
- Keep a map to keep track of answer for each cell of the grid.
Below is the implementation of the above approach:
Time Complexity : O(N*p*p)