Skip to problem
←

Shortest Bridge

Medium 0 attempts

Given an n × n binary grid containing exactly two islands, return the fewest water cells you must flip from 0 to 1 to connect them.

An island is a maximal group of land cells (1s) connected horizontally or vertically. Diagonal contact does not connect islands. You may start your bridge from any cell of either island.

Count only flipped water cells, not existing land cells. For [[0,1],[1,0]], flipping either zero connects the two diagonal land cells, so the answer is 1.

Function contract

Implement shortestBridge(grid).

Output: Return the minimum number of water cells (0s) to flip to connect the two islands using horizontal or vertical adjacency.

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
Visual Aid
A bridge needs three water cells
100000001

For opposite corners of a 3 × 3 grid, one shortest route flips the three outlined water cells. The two existing land cells are not counted.

Constraints
  • grid is n × n, with 2 <= n <= 100
  • grid[i][j] is 0 or 1
  • Exactly two islands
Topics

Iterative Flood Fill and Multi-Source BFS

Mark one entire island with an explicit stack, then expand from all its cells simultaneously. Each BFS layer crosses one additional water cell. The first contact with the other island gives the minimum number of flips.

javascript
function shortestBridge(grid) {
  const n = grid.length, q = [], dirs = [[0,1],[0,-1],[1,0],[-1,0]];
  function markIsland(r, c) {
    const stack = [[r,c]]; grid[r][c] = 2;
    while (stack.length) {
      const [x,y] = stack.pop(); q.push([x,y]);
      for (const [dx,dy] of dirs) {
        const nx=x+dx,ny=y+dy;
        if(nx>=0&&nx<n&&ny>=0&&ny<n&&grid[nx][ny]===1) {
          grid[nx][ny]=2;stack.push([nx,ny]);
        }
      }
    }
  }
  outer: for (let i=0;i<n;i++) for (let j=0;j<n;j++) if (grid[i][j]===1) { markIsland(i,j); break outer; }
  let steps = 0;
  let head = 0;
  while (head < q.length) {
    const size = q.length - head;
    for (let k=0;k<size;k++) {
      const [r,c] = q[head++];
      for (const [dr,dc] of dirs) {
        const nr=r+dr, nc=c+dc;
        if (nr>=0&&nr<n&&nc>=0&&nc<n) {
          if (grid[nr][nc]===1) return steps;
          if (grid[nr][nc]===0) { grid[nr][nc]=2; q.push([nr,nc]); }
        }
      }
    }
    steps++;
  }
  return steps;
}

Time: O(n²) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript