Skip to main content
LeetCode 1568, Hard. Topics: Array, Depth-First Search, Breadth-First Search, Matrix, Strongly Connected Component, Articulation Point. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 40 parametrized pytest cases, and a playground notebook:

Problem

You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1s. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid.

Examples

Example 1
Example 2

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 30
  • grid[i][j] is either 0 or 1.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026