
Input: ‘N’ = 2 ,'GRID' = [[0,1],[1,1]]
Output: 4
Explanation:
Sam can plant a tree on the only remaining unplanted cell.
The first line of the input contains an integer, ‘T’, denoting the number of test cases.
The first line of each test case contains an integer, 'N’, denoting the size of the (NxN)campus.
The next ‘N’ lines of each test case contain N integers (0 or 1), denoting unplanted and plated area.
Return an integer, denoting the largest group of trees on the campus after Sam planted a tree.
1 <= T <= 10
1 <= N <= 500
GRID[i][j] is either 0 or 1.
Time Limit: 1 sec
The solution to the problem lies in counting the number of connected components in the GRID using the data structure Disjoint Set Union and now we can check for the contributions of 0s to the number of trees and return the largest group. The implementation for the DSU is as follows:
We can check the contribution of each 0 to its neighboring tree groups and the maximum contributing 0 can be included in our answer.
For each group of trees, we will give them a unique id and map each id with the number of trees in that group. Now we will iterate the GRID and go to each 0, and check for all the 4 directions, if we can get a group of trees then we will increase their count by 1. At last, we can return the largest group of trees formed.