Shortest Bridge to Join the Two Islands on a Map Grid

Last updated: November 29, 2026

Quick Overview

A binary grid contains exactly two 4-connected islands of 1s. Return the minimum number of 0 cells you must flip to 1 to connect them into one island.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A binary grid contains exactly two 4-connected islands of 1s. Return the minimum number of 0 cells you must flip to 1 to connect them into one island.

An onsite question combining two traversals: a DFS to label one island and a multi-source BFS to expand from it. Google interviewers watch for candidates who try a BFS from every cell of island one separately, which is much slower.

What the Interviewer Expects
  • Find and mark the first island with DFS or BFS
  • Seed a multi-source BFS with all cells of that island
  • Expand through water layer by layer
  • Stop when the BFS touches the second island
  • Return the number of water layers crossed
Key Topics to Cover
DFS
multi-source BFS
grid
connected components
shortest path
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if there are k islands and you want the cheapest way to connect all of them?
  • What if crossing some water cells costs more than others?
  • Return the actual cells of the bridge.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: n by n grid, exactly two islands.
  • Flip water cells to connect them; minimize flips.
  • 4-directional adjacency.
  • Mutation of the input is acceptable if stated....
High-Level Design

Phase 1: find any land cell, then flood its island, marking cells as 2 and collecting them. Phase 2: run BFS with all of those cells in the initial queue at distance 0. Expanding level by level throug...


Submit Your Answer
Markdown supported