Ctrl K

Fill a Single Cell

Hard
A map of an archipelago is an n × n grid land: 1 is land and 0 is water. An island is a group of land cells connected through their sides (up, down, left, right); diagonal contact does not count. You have enough soil for exactly one cell: you may turn at most one water cell into land (or change nothing). Return the size (number of cells) of the largest island you can end up with.
Example 1
land=[[1, 1, 0], [0, 0, 1], [1, 1, 1]] → 7

There are islands of size 2 (top left) and 4. Filling the centre cell joins both of them: 2 + 4 + 1 = 7.

Example 2
land=[[1, 0, 1], [0, 0, 0], [1, 0, 1]] → 3

Four one-cell islands. Filling the cell between two neighbouring corners gives an island of 3 cells.

Example 3
land=[[0, 0], [0, 0]] → 1

There is no land at all, but filling one cell creates an island of size 1.

Constraints
  • n == len(land) == len(land[i])
  • 1 ≤ n ≤ 500
  • land[i][j] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCrossing at High Tide HardLast Dry Crossing Day HardDrain the Landlocked Ponds MediumLand Regions on a Map MediumLargest Forest Patch Medium
loading Python…
Input
land=[[1, 1, 0], [0, 0, 1], [1, 1, 1]]
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 83 tests on the server, hidden ones included.