Find shortest distance between two islands
CoupangSoftware Engineer · OnsiteLast updated
This question evaluates understanding of grid-graph traversal and shortest-path concepts, including identification of connected components and reasoning about minimal bridging distance between regions.
Problem
You are given an R x C binary grid where:
1represents land0represents water
The grid contains exactly two 4-directionally connected islands (connected via up/down/left/right). You may flip water cells (0) into land (1).
Return the minimum number of water cells to flip so that the two islands become connected (i.e., there exists a 4-directional path of 1s between them).
Input
grid: 2D array of integers (0or1)
Output
- An integer: the minimum number of flips needed.
Constraints (reasonable interview assumptions)
1 <= R, C <= 200- Exactly two islands exist.
Example
If flipping a single 0 cell can connect the islands, return 1.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.