← Visualizers
Graphs · Multi-source BFS — when the sources are not given LeetCode 934

Shortest Bridge / visualized

994 hands you the rotten oranges, 542 hands you the zeros, 1162 hands you the land. Here nobody hands you anything: you must run a whole first traversal — a DFS, exactly the one in LC 200 — just to discover the seed set, and only then does the machine from the other three pages apply. Phase one paints one island; phase two floods outward from every cell of it at once. The bridge is the water flipped, so the answer is levels minus one — level 1 is the island itself and flips nothing.

Execution

idle
INVARIANT DFS + Multi-Source BFS Composition: Phase 1 uses DFS to isolate Island A and push EVERY cell into queue. Phase 2 radiates concentric BFS waves into water until touching Island B. First contact yields minimum flips (level - 1).
phase one · DFS: which cells are island A
Press Run to begin.
0 / 0
Speed

Java · running line

scan cursor current cell island A — every cell a source flooded water · ring number the bridge itself painted but never seeded water
INTERVIEW SCRIPT

How to Explain Shortest Bridge to an Interviewer

1. Two Connected Components

"The problem guarantees exactly two disconnected islands of 1s. The goal is to find the minimum number of 0s that need to be flipped to connect them."

2. Phase 1: DFS to Discover Island A

"Scan the grid until the first 1 is encountered. Launch DFS to traverse all contiguous 1s belonging to Island A, flipping them to 2 (to mark visited) and pushing every coordinate into a BFS queue."

3. Phase 2: Multi-Source BFS Waves

"Radiate outwards from ALL Island A cells simultaneously in concentric BFS waves through water (0s). The moment a wave steps onto a cell containing 1, it has reached Island B!"

4. Why level - 1?

"Level 1 is Island A itself, which requires 0 flips. Each subsequent BFS level flips one layer of water cells. Therefore, flips required = level - 1."

O(m·n) time and space  ·  the flood flips far more water than the bridge contains — the bridge is one shortest chain through the rings, and its length is level − 1, because level 1 is island A itself and costs nothing. Seeding one cell instead of all of them still often returns the right number, which is precisely why it survives testing.