Making a Large Island

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

Return the size of the largest island in grid after applying this operation.

An island is a 4-directionally connected group of 1s.

Examples

Example 1:

Input: grid = [[1,0],[0,1]]

Output: 3

Explanation: Change one 0 to 1 and connect two 1s to create an island of size 3.

Example 2:

Input: grid = [[1,1],[1,0]]

Output: 4

Explanation: Change the 0 to 1 to make an island of size 4.

Example 3:

Input: grid = [[1,1],[1,1]]

Output: 4

Explanation: No 0 to change, the entire grid is already one island of size 4.

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 500
  • grid[i][j] is either 0 or 1
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle