Making A Large Island

You are given an n x n binary matrix grid. You may change at most one 0 to a 1. Return the size of the largest island in grid after applying this operation. An island is a group of 1s connected 4-directionally.

30:00

Making A Large Island
hard
Free written solution
Topics
Companies

You are given an n x n binary matrix grid. You may change at most one 0 to a 1. Return the size of the largest island in grid after applying this operation. An island is a group of 1s connected 4-directionally.

Example 1:
Input: {"grid":[[1,0],[0,1]]}
Output: 3
Constraints:
  • n==grid.lengthn == \text{grid.length}

  • n==grid[i].lengthn == \text{grid}[i].\text{length}

  • 1≤n≤5001 \leq n \leq 500

  • grid[i][j]\text{grid}[i][j] is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[1,0],[0,1]]}

The grid is 2 x 2 with 2 land cells. First give every island its own id (2, 3, ...) and record its area.

1

1

size[id] (island areas)

no islands labelled yet

flip this water cell

labelling islands first

best

-

Variables
VariableValue
n2
islands0
best0
DepthFunction Call
Stack empty
0/8