For an empty lot , let be the number of houses among its at most neighboring cells.
If one tree is planted on , that tree is counted once for every adjacent house. Therefore it increases the required total by exactly . Contributions from different empty lots are independent.
The task is thus to choose some values , each between and , so that their sum is at least while minimizing how many values are chosen. For any fixed number of chosen lots, the largest possible sum is obtained by taking the largest values first. Hence it is optimal to take lots in the order .
If the sum of over all empty lots is smaller than , the requirement is impossible and the answer is -1. If , the answer is .
Each is found by checking at most neighboring cells. Since only the values are possible, it is enough to count the frequency of each value; sorting is unnecessary. The time complexity is per test case and overall. The grid uses memory.
Solution written by GPT5.6