Find shortest distance between two islands
Company: Coupang
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: 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.
Constraints
- 1 <= R, C <= 200
- grid[i][j] is either 0 or 1
- There are exactly two islands in the grid
- Cells are connected only in 4 directions: up, down, left, and right
Examples
Input: ([[0, 1], [1, 0]])
Expected Output: 1
Explanation: The two islands are diagonally adjacent. Flipping either (0,0) or (1,1) connects them.
Input: ([[0, 1, 0], [0, 0, 0], [0, 0, 1]])
Expected Output: 2
Explanation: A shortest connection flips two water cells, such as (1,1) and (1,2).
Hints
- First, find one of the islands and mark all of its cells.
- Then run a multi-source BFS starting from every cell of that island at once. The first time you reach the other island gives the minimum number of flips.