KatInterview

Largest Land Mass After One Water-to-Land Conversion

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraphbfs-dfsconnected-components

Last updated

Tests grid connected-component labeling and the ability to optimally merge adjacent island regions by flipping a single water cell to land.

You are given an n × n binary grid where 1 represents land and 0 represents water. Cells are connected in four cardinal directions (up, down, left, right); diagonal adjacency does not count.

You may convert at most one water cell (0) into a land cell (1). Return the size of the largest possible land mass (connected component of 1s) after this optional conversion.

If converting a water cell causes previously separate islands to touch, they merge into a single land mass through the converted cell.

Rules and Edge Cases

  • You are not required to flip any cell. If every cell is already land, return the size of the existing land mass.
  • If no land exists at all, flipping any single water cell produces a land mass of size 1, so return 1.
  • If the grid is empty, return 0.
  • When a water cell borders the same island from multiple sides (for example, a U-shaped island wrapping around a gap), that island's size must be counted only once in the merged total.

Constraints

  • 1 ≤ n ≤ 1000
  • grid[i][j] is either 0 or 1
  • The grid is square (n rows and n columns)
  • Your solution must run in O(n²) time and use O(n²) or better space
  • Do not use recursive depth-first search on large grids; Python's default call stack will overflow on grids up to n = 1000

Examples

Example 1

Input: max_island_one_conversion([[1, 0], [0, 1]])

Output: 3

Example 2

Input: max_island_one_conversion([[1, 1], [1, 0]])

Output: 4

Example 3

Input: max_island_one_conversion([[0, 0], [0, 0]])

Output: 1

Example 4

Input: max_island_one_conversion([[1, 1], [1, 1]])

Output: 4

Hints

Hint 1

In a first pass, assign every island a unique integer ID and record how many cells each island contains. A cell value of 0 stays unlabeled (ID 0).

Hint 2

For each water cell, gather the IDs of all labeled neighbors into a set — not a list — before summing their sizes. The set prevents counting the same island twice when it wraps around the water cell.

Hint 3

Track the largest island found during labeling. That value is your answer when no flip improves things (or when there are no water cells at all), so initialize your running best to it before scanning water cells.