Problem of the day
Sam is on a plantation drive on his campus. His campus can be represented as an ‘N’x’N’ ‘GRID’ of 0s and 1s. Where cells with 1 represent that there is already a tree and cells with 0 represent that a tree can be planted here.
Sam wants to plant atmost 1 tree in his campus.
Note : It is possible that the grid does not contain any zero.
Return the largest group of trees on the campus after Sam planted 1 tree.
Largest group of trees is the 4-directionally connected group of 1s.
Example: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.
Output format :
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
2
2
0 1
1 1
3
1 0 1
0 0 0
0 0 0
4
3
Test 1:
Sam can plant a tree on the only remaining unplanted cell.
Test 2:
Sam can plant a tree between the two trees, so the largest group would contain 3 trees.
2
2
0 0
0 0
3
0 1 0
1 0 1
0 1 0
1
5
Check for the connected components using disjoint sets.
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:
The steps are as follows :
Function makeSet(int element, parent[int])
Function findSet(int element, parent[int])
Function unionSet(int element1, int element2, [int]parent, [int]rank)
Function connectedComp(int N,[int][int]GRID)
O(N^2 x log(N)), Where ‘N’ is the number of rows or columns in the GRID.
We are performing the union for every element in the NxN GRID.
Hence the time complexity is O(N^2 x log(N)).
O( N x N ), Where ‘N’ is the number of rows or columns in the GRID.
We are maintaining parent and rank arrays, whose length may be NxN in the worst case.
Hence the space complexity is O( N x N ).