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

Problem

You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s.

Examples

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 500
  • 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