Making a large island

Graphs Hard Problems II Hard
  • Fun fact: The underlying concept of this programming problem is extensively used in image processing applications and computer vision
  • Specifically, these applications use morphological operations which can include expanding the area of a unique color (akin to changing a 0 to a 1 in the problem) and then determining the size of the largest connected component (or the largest island)
  • This can help in identifying and tracking objects or features in an image or video stream
  • This technique can be used in a variety of industries such as surveillance systems, autonomous vehicle systems, medical imaging processing, and more!

Given an n x n binary matrix grid, it is allowed to change at most one 0 to 1. A group of connected 1s forms an island, where two 1s are connected if they share one of their sides.


Return the size of the largest island in the grid after applying this operation.

Examples:

Input: grid = [[1,0],[0,1]]

Output: 3

Explanation: We change any one 0 to 1 and connect two 1s, then we get an island with maximum area = 3.

Input: grid = [[1,1],[1,1]]

Output: 4

Explanation: The largest island already exists with size 4.

Input: grid = [[1,1],[1,0]]

Constraints

  • 1 <= n <= 500
  • 0 <= grid[i][j] <= 1 

Hints

  • "Label each island with a unique index using DFS and store its size in a hashmap {island_id: size}. For every 0 in the grid, check its adjacent 1s (up, down, left, right). The answer is the maximum size of any modified island. "
  • "Instead of running DFS/BFS for every possible 0 flip, we precompute all islands first and store their sizes. Each 0 can be flipped into 1, and we check how many distinct islands it connects to. The goal is to find a 0 that maximizes the total merged island size."

Company Tags

Square Freshworks Micron Technology Epic Systems Instacart IBM PwC Red Hat American Express Teladoc Health PayPal Intel Oracle Ernst & Young MongoDB Activision Blizzard Etsy NVIDIA Zynga Robinhood Boston Consulting Group Snowflake Databricks Swiggy Goldman Sachs Google Microsoft Amazon Meta Apple Netflix Adobe