You are given an 'n' x 'n' binary matrix 'grid'.
You are allowed to change at most one '0' to be '1'. Your task is to find the size of the largest island in the grid after applying this operation.
An island is a 4-directionally (North, South, East, West) connected group of 1s.
Input: 'grid' = [[1,0],
[0,1]]
Output: 3
Explanation:
We can change the 0 at (0,1) to 1 and get an island of size 3.
The first line of each test case contains an integer 'n', representing the number of rows and columns in 'grid'.
Each of the next 'n' lines contain 'n' elements each denoting the values of the grid.
Return the largest size of the island in the grid after applying the given operation at most once.
You do not need to print anything, it has already been taken care of. Just implement the given function.
2
0 1
1 0
3
3
For this test case,
If we change the 0 at (1,1) to 1, then we get an island with size 3.
4
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1
1
Try to do this in O(n^2).
1 <= n <= 500
0 <= grid[i][j] <= 1
Time Limit: 1 sec
Can you solve this problem using Depth-first search?
Approach:
Algorithm:
Since we are traversing over each element of the matrix, and we are calling DFS for every 0 encountered which takes O(N^2) time for each call. Hence, the overall Time Complexity is O(N^4).
In the worst case, O(N) space is used by the recursion stack formed during DFS traversal, and also, the visited array used for DFS takes O(N^2) space. Hence, the overall Space Complexity is O(N^2).