Fewest Cells to Fill to Join Two Separate Land Masses
Last updated: November 29, 2026
Quick Overview
A binary grid contains exactly two islands of 1s connected four-directionally. Return the minimum number of 0 cells that must be flipped to 1 to connect them.
Meta
November 29, 20260
0
0 solved
A binary grid contains exactly two islands of 1s connected four-directionally. Return the minimum number of 0 cells that must be flipped to 1 to connect them.
A Meta onsite grid question that chains two traversals: one to label an island and one multi-source BFS to expand from it. It could be framed as connecting two map regions in a Meta Maps style tool. Interviewers check that you start the BFS from the whole island at once rather than from one cell.
What the Interviewer Expects
- Find and mark the first island with DFS or BFS
- Seed a BFS with every cell of that island at distance 0
- Stop at the first cell belonging to the second island
- Explain why multi-source BFS gives the minimum flips
- Keep memory linear in grid size
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if there were k islands and you wanted to connect them all cheaply?
- How would you return which cells to flip?
- What if flipping some water cells cost more than others?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Square or rectangular grid up to 100 x 100 with exactly two islands.
- Flip water cells so that the islands touch four-directionally.
- Return the minimum number of flips....
High-Level Design
The cost of connecting is the shortest grid distance between any cell of island A and any cell of island B, minus one. Collect island A with an iterative DFS, then run BFS starting from all its cells ...