{x}
blog image

Making A Large Island

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.

 

Example 1:

Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.

Example 3:

Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

 

Constraints:

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

Solution Explanation: Making a Large Island

This problem asks to find the largest island (connected component of 1s) in a binary matrix after changing at most one 0 to 1. The optimal solution uses Depth-First Search (DFS) or Breadth-First Search (BFS) along with Union-Find (though the provided solutions primarily use DFS).

Approach

The solution involves two main steps:

  1. Island Identification and Sizing: First, we iterate through the grid. Whenever we find a '1' that hasn't been visited (belonging to an unlabeled island), we perform a DFS (or BFS) to explore its connected component. This DFS assigns a unique identifier (a root value) to all cells in that island and simultaneously calculates the size (cnt[root]) of that island.

  2. Maximizing Island Size by Flipping a Zero: After labeling all islands, we iterate through the grid again. For each '0', we check its four neighbors. If they belong to different islands, we calculate the potential size of a new, larger island by summing the sizes of those neighboring islands and adding 1 (for the '0' we're flipping). We keep track of the maximum size found in this step.

Time and Space Complexity

  • Time Complexity: O(N^2), where N is the number of rows/columns in the grid. Both the island identification and the flipping-zero steps iterate through the grid once. The DFS (or BFS) within island identification takes at most O(N^2) time in the worst case (a single large connected component).

  • Space Complexity: O(N^2). This is primarily due to:

    • The p array (or similar data structure) used to store island identifiers.
    • The cnt array (or similar data structure) used to store island sizes.
    • The recursion stack in DFS (in the worst case, it can be proportional to N^2 if there's one giant island).

Code Explanation (Python)

The Python code provided uses a dfs function for island identification and sizing.

class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        def dfs(i: int, j: int):
            p[i][j] = root
            cnt[root] += 1
            for a, b in pairwise(dirs): # pairwise iterates through adjacent cells
                x, y = i + a, j + b
                if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0:
                    dfs(x, y)
 
        # ... (rest of the code as in the problem statement)

The dfs function recursively explores connected components. The main part of the code then iterates twice: once to label islands, and once to check potential improvements by changing a single '0' to '1'.

The pairwise function is helper function which likely iterates over adjacent cells (up, down, left, right). Its implementation would need to be included for the code to run completely.

Code in Other Languages

The problem statement includes solutions in Java, C++, Go, and TypeScript. These solutions follow the same algorithm but are adapted to the syntax and data structures of their respective languages. The core logic of island identification using DFS and the subsequent optimization by flipping a zero remains consistent across all implementations.