Making A Large Island

Given a binary grid, you may change at most one 0 to 1. Return the size of the largest island that can be formed. Pattern focus: Connected. The problem is solved by labeling connected components and combining neighboring ones efficiently.

Input Format

grid = binary matrix

Output Format

largest possible island size after at most one flip

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • grid must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

grid = [[1,0],[0,1]]

Output:

3

Explanation:

Flipping one 0 can connect two diagonally separated single-cell islands through adjacency.

Example 2:

Input:

grid = [[1,1],[1,0]]

Output:

4

Explanation:

Flipping the last cell creates a 4-cell island.

Loading...
Making A Large Island - Graph Fundamentals