1096. Shortest Bridge

HardGraphsBFSGridGraph

Given a grid containing exactly two islands (4-directionally connected groups of 1s) in a sea of 0s, return the minimum number of 0s that must be flipped to 1 to connect the two islands. The input is JSON {grid}.

Input: JSON {grid}.

Output: Integer — the minimum flips to bridge the islands.

Examples

Example 1
Input: {"grid":[[0,1,0],[0,0,0],[0,0,1]]}
Output: 2
Explanation: Two cells bridge the islands.
Example 2
Input: {"grid":[[1,0],[0,1]]}
Output: 1
Explanation: One cell connects them.
Example 3
Input: {"grid":[[1,1,0,0],[0,0,0,1]]}
Output: 2
Explanation: Two flips needed.

Constraints

Asked by

FlipkartMetaGoogleAmazonMicrosoftBloomberg
Solve this problem in the editor →