Problem Description
Given an n x n binary matrix where 1 represents land and 0 represents water, there are exactly two separate islands (i.e. groups of 4-directionally connected 1's). The goal is to flip 0's into 1's to connect these two islands with the fewest number of flips possible. You must determine the minimum number of 0’s that need to be flipped to connect the two islands.
Key Insights
- First identify one of the islands and mark all its cells. This is commonly done using Depth-First Search (DFS) or Breadth-First Search (BFS).
- Once the first island is identified, use multi-source BFS starting from every cell in that island simultaneously.
- Expand the BFS level by level until any cell from the second island (cell value 1 that is not marked) is encountered. The BFS level at which you first find the second island equals the minimum number of flips required.
Space and Time Complexity
Time Complexity: O(n^2) – In the worst-case, every cell in the grid may be processed once. Space Complexity: O(n^2) – In the worst-case, the space used by the recursion (DFS) or the BFS queue can hold a large fraction of the grid cells.
Solution
The solution first locates one island by scanning the grid and performing DFS from the first encountered land cell. During DFS, mark every cell of the island (e.g. by changing its value to 2) and add it to a BFS queue. Then, execute a BFS starting from the entire first island simultaneously. In each BFS level, examine all neighboring cells; if a neighboring cell belongs to the second island (i.e., its value is 1), the current BFS level represents the answer. If a neighboring cell is water (0), mark it (so it is not processed again) and add it to the BFS queue. Continue this until the second island is reached. Key data structures used include a queue for multi-source BFS and recursive function calls for DFS traversal.
Code Solutions
Below are the code solutions in Python, JavaScript, C++, and Java with detailed line-by-line comments.