Skip to main content
LeetCode 934, Medium. Topics: Array, Depth-First Search, Breadth-First Search, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:

Problem

<p>You are given an <code>n x n</code> binary matrix <code>grid</code> where <code>1</code> represents land and <code>0</code> represents water.</p> <p>An island is a 4-directionally connected group of <code>1</code>‘s not connected to any other <code>1</code>‘s. There are <strong>exactly two islands</strong> in <code>grid</code>.</p> <p>You may change <code>0</code>‘s to <code>1</code>‘s to connect the two islands to form <strong>one island</strong>.</p> <p>Return <em>the smallest number of </em><code>0</code><em>‘s you must flip to connect the two islands</em>.</p>

Examples

Constraints

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is either 0 or 1.
  • There are exactly two islands in grid.

Solution

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

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026