Minimum Number of Days to Disconnect Island

Hard Topics Company Tags

In the binary grid, 1 represents land and 0 represents water. An island is a group of land cells connected through shared edges. The grid is connected only when it has exactly one island; both zero islands and multiple islands count as disconnected. Each day, you may change one land cell into water. Return the fewest days needed to make the grid disconnected.

Example 1:

Minimum Number of Days to Disconnect Island, example 1: illustration of the example

Input: grid = [[1,0,1]]

Output: 0

Explanation: The two land cells are already separate islands. The grid is disconnected before any changes, so the answer is 0.

Example 2:

Minimum Number of Days to Disconnect Island, example 2: illustration of the example

Input: grid = [[1,1,1]]

Output: 1

Explanation: Change the middle cell to water. The remaining two land cells form separate islands, so 1 day is enough.

Example 3:

Minimum Number of Days to Disconnect Island, example 3: illustration of the example

Input: grid = [[1,1],[1,1]]

Output: 2

Explanation: Removing any one cell leaves a connected three-cell island. Removing two diagonally opposite cells leaves two separate islands, so the minimum is 2 days.

Constraints:

  • 1 <= grid.length <= 30
  • Every row has the same length, between 1 and 30.
  • Each entry is either 0 (water) or 1 (land).


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.