Skip to the code
cf.
+25 XP

#428 Shortest Bridge Between Two Shapes

medium

A level editor has a grid of strings where "#" is ground and "." is water. Ground cells that touch up, down, left, or right form an island, and the grid has exactly two islands.

Write shortestBridge(grid) that returns the fewest water cells you must turn into ground so that the two islands become connected.

Example 1

Input: grid = ["#..","...","..#"]
Output: 3

The islands are 4 steps apart, so 3 water cells between them must be filled, for example (0, 1), (0, 2), and (1, 2).

Example 2

Input: grid = ["#.#"]
Output: 1

Fill the single water cell in the middle.

Constraints

  • 2 <= rows * cols <= 10000
  • There are exactly two islands.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).