


The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, where ‘N’ and ‘M’ denote the dimensions of the binary grid. Then ‘N’ lines follow.
Each of these ‘N’ lines contains ‘M’ space-separated integers denoting the elements of the ‘i-th’ row. Each of these integers is either a 0 or a 1.
The next line contains two space-separated integers, ‘K’ and ‘Q’, where ‘K’ denotes the maximum number of 1s that a square can have and ‘Q’ denotes the number of queries to be run. Now, ‘Q’ lines follow.
Each of these ‘Q’ lines contains two space-separated integers, ‘A’ and ‘B’, denoting that in this query, the required square must have the cell located at ‘A-th’ row and ‘B-th’ column as its center.
For each test case, print ‘Q’ space-separated integers, denoting the length of the largest required square in each query.
Output for each test case will be printed in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N,M <= 500
1 <= Q <= 1000
1 <= K <= N*M
Where ‘T’ denotes the number of test cases and ‘N’ and ‘M’ denote the dimensions of the binary grid. ‘Q’ denotes the number of queries and ‘K’ is the maximum number of 1s that the required square can have.
Time Limit: 1 sec.
The approach is to simply try to solve each query independently. We will start at the given cell and count the number of 1s in it and one by one count the number of 1s in each square whose center is that cell. As soon as this count becomes greater than ‘K’ we stop and return the length of the previous square because the required square is allowed to have not more than ‘K’ 1s.
The approach is to use Dynamic Programming to avoid recalculating the number of 1s present in any given square. With the help of some precalculations, we can find out the number of 1s efficiently. We can also further optimize our solution by using binary search instead of increasing the length of the possible squares one by one.
Matrix Block Sum
Minimized Maximum of Products Distributed to Any Store
Optimal Itinerary for Maximum Profit
Count of Subsequences with Given Sum
Optimal Line Arrangement