KatInterview

Best Plot After Reclaiming a Single Water Tile

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsgridflood-fillconnected-components

Last updated

Find the largest connected land region achievable by turning at most one water cell into land, which tests component labeling and merging neighbors without double counting.

Best Plot After Reclaiming a Single Water Tile

A map is stored as a rectangular grid of integers. A 1 is a land tile and a 0 is a water tile. Land tiles that are adjacent horizontally or vertically belong to the same landmass. Tiles that touch only at a corner are not connected.

You may reclaim at most one water tile, turning it into land. You may also choose to reclaim nothing. Return the number of tiles in the largest landmass that can exist after your choice.

Details

  • The size of a landmass is the number of tiles it contains.
  • If the grid contains no water, the answer is simply the total number of tiles.
  • If the grid contains no land, reclaiming any one tile gives a landmass of size 1.
  • Reclaiming a water tile merges it with every landmass that is directly adjacent (up, down, left, right). If the same landmass touches the tile on several sides, its tiles are counted only once.

Function

Implement biggest_landmass_with_one_reclaim(grid), where grid is a list of rows, each a list of 0/1 integers. Return a single integer: the largest possible landmass size.

Constraints

  • 1 <= len(grid) <= 500
  • 1 <= len(grid[i]) <= 500, and all rows have the same length
  • Every grid[i][j] is 0 or 1
  • The answer is at most 250000

Examples

Example 1

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

Output: 3

Example 2

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

Output: 4

Example 3

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

Output: 5

Hints

Hint 1

Reclaiming a water tile never changes the existing landmasses by itself; it only joins the ones next to it. So you can compute landmass sizes once and reuse them.

Hint 2

Label each landmass with an id and store its size. Then, for each water tile, look at its four neighbors and gather the ids.

Hint 3

A water tile may touch the same landmass on more than one side. Add each distinct id's size only once, plus 1 for the reclaimed tile itself. Do not forget the answer when no change is made, and avoid deep recursion on large grids.