here is the link
https://www.codechef.com/viewsolution/21144157
Values of N and M for 2nd Subtask can be upto 300. So, if every cell contains a 1 then there will be {300*300}=9*10^4 houses and you’re computing distance for every pair of houses, so that would be (9*10^4)^2=8.1*10^9 per test case, and there can be upto 3 test cases which makes overall complexity of your solution equals to 2.4*10^{10}, and clearly you can’t compute that in 3 seconds.