Class Solution

java.lang.Object
g0901_1000.s0934_shortest_bridge.Solution

public class Solution extends Object
934 - Shortest Bridge.

Medium

You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1โ€™s not connected to any other 1โ€™s. There are exactly two islands in grid.

You may change 0โ€™s to 1โ€™s to connect the two islands to form one island.

Return the smallest number of 0โ€™s you must flip to connect the two islands.

Example 1:

Input: grid = [[0,1],[1,0]]

Output: 1

Example 2:

Input: grid = [[0,1,0],[0,0,0],[0,0,1]]

Output: 2

Example 3:

Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]

Output: 1

Constraints:

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is either 0 or 1.
  • There are exactly two islands in grid.
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • shortestBridge

      public int shortestBridge(int[][] grid)