AlgoMaster Logo

Making A Large Island

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

In this initial approach, the goal is to change each 0 in the grid to 1 one by one and calculate the size of the island it can form. For each conversion, we calculate the potential size of the island and keep track of the maximum size encountered. The key idea is to perform a depth-first search (DFS) to calculate the size of each connected component (island).

Steps:

  1. For each cell in the grid that contains a 0, temporarily change it to a 1.
  2. Use DFS to calculate the size of the island this change creates.
  3. Restore the cell back to 0 and continue to the next 0.
  4. Return the maximum island size found.

Code:

2. Optimized Approach with Connected Components

Intuition:

To optimize, pre-calculate the sizes of all connected components (islands) and then analyze the potential contributions of each 0 within the grid. We use different numeric IDs for different islands and store the size corresponding to each ID. This approach reduces unnecessary recalculations.

Steps:

  1. Assign unique IDs to each connected component using DFS and calculate their sizes.
  2. Store these sizes in a map with the ID as the key.
  3. For each 0, check its 4 neighboring cells and sum the sizes of distinct islands formed by adjacent 1s.
  4. The maximum size achieved by flipping a 0 is stored as the result.

Code: