Best Bridge

Best Bridge

A grid contains exactly two islands of land (L) separated by water (W). Return the minimum number of water cells you must turn into land to connect the two islands (the length of the shortest bridge).

bestBridge(grid)

Input format: rows separated by |.

Examples

LWL              // → 1
LWWL             // → 2
LL|WW|LL         // → 1

Walkthrough

Breaking a hard problem into two familiar pieces

This looks intimidating, but it decomposes into two techniques you've already built: flood-filling an island, and BFS for shortest distance across water. The trick is combining them, adapting the BFS to start from many cells at once.

Step one: find and collect one whole island

Scan the grid until you find any land cell — either island works, since both are symmetric. Flood-fill outward exactly as in island counting, but this time collect every cell into a list instead of just marking and discarding. That list is the entirety of "island one," and every cell in it is a valid starting point for reaching island two.

Step two: reframe the bridge question as a shortest-path question

Once you have island one's cells, the question becomes: starting simultaneously from every cell of island one, what's the fewest water-cell steps to reach the other island? Still an unweighted shortest-path question, so BFS is still right — the twist is seeding the queue with the entire first island at distance 0 at once. This is multi-source BFS: since all of island one starts at distance 0, the search measures distance purely in water crossed, not land already owned.

Why multi-source BFS still guarantees the shortest bridge

BFS's ring-by-ring expansion holds regardless of how many starting points you seed — it still explores all cells at true distance 1 from any source before distance 2, and so on. So the first time the frontier reaches a land cell not part of the original island (necessarily the second island), the water steps taken is the shortest possible bridge.

Why you mark the whole first island visited before starting the BFS

Since every cell of island one is already "free" (distance 0), mark them all visited before the BFS begins, so the search doesn't waste time on movement within the first island or re-add its cells to the queue.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.