![]() |
VOOZH | about |
Given a binary matrix of size n x n, the task is to find the largest island after changing at most one cell from 0 to 1.
Note: An island is a 4-directionally (i.e, up, down, right, left) connected group of 1s.
Examples:
Input: grid = {{1 1},
{0 1}}
Output: 4
Explanation: By changing cell (2,1) ,we can obtain a connected group of 4 1'sInput: grid = {{1 0 1},
{1 0 1},
{1 0 1}}
Output: 7
Explanation: By changing cell (3,2) ,we can obtain a connected group of 7 1'sInput: grid = { { 1, 0, 1, 1, 0 },
{ 1, 0, 0, 1, 0 },
{ 0, 1, 1, 0, 1 },
{ 1, 0, 1, 0, 1 },
{ 0, 1, 0, 1, 0 } };
Output: 9
Naive approach: The basic way to solve the problem is as follows:
The idea to solve the problem is to use DFS. For each water cell (i.e, grid[i][j] = 0's ) maximise the result by summation of all unique neighbour's island size + 1 (i.e, we add 1 extra because we also have to convert the current water cell into land.
Follow the steps below to implement the above idea:
Below is the implementation of the above approach:
Largest island size: 9
Time Complexity: O(n4)
Auxiliary Space: O(n2)
The idea is to keep track of each island by some unique identity say key/name with its size. After this, go through each cell which is water (i.e, matrix[i][j] == 0) and add the sizes of unique neighbour's island into current size, finally maximize the currentsize in the result.
Follow the steps below to implement the above idea:
Below is the implementation of the above approach:
Largest island size: 9
Time Complexity: O(n2)
Auxiliary Space: O(n2)