Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.
You may change 0's to 1's to connect the two islands to form one island.
Return the smallest number of 0's you must flip to connect the two islands.
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
Example 3:
Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1
Constraints:
n == grid.length == grid[i].length2 <= n <= 100grid[i][j] is either 0 or 1.grid.Problem summary: You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[0,1],[1,0]]
[[0,1,0],[0,0,0],[0,0,1]]
[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
minimum-number-of-operations-to-make-x-and-y-equal)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #934: Shortest Bridge
class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
private Deque<int[]> q = new ArrayDeque<>();
private int[][] grid;
private int n;
public int shortestBridge(int[][] grid) {
this.grid = grid;
n = grid.length;
for (int i = 0, x = 1; i < n && x == 1; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
dfs(i, j);
x = 0;
break;
}
}
}
int ans = 0;
while (true) {
for (int i = q.size(); i > 0; --i) {
var p = q.pollFirst();
for (int k = 0; k < 4; ++k) {
int x = p[0] + dirs[k], y = p[1] + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n) {
if (grid[x][y] == 1) {
return ans;
}
if (grid[x][y] == 0) {
grid[x][y] = 2;
q.offer(new int[] {x, y});
}
}
}
}
++ans;
}
}
private void dfs(int i, int j) {
grid[i][j] = 2;
q.offer(new int[] {i, j});
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1) {
dfs(x, y);
}
}
}
}
// Accepted solution for LeetCode #934: Shortest Bridge
func shortestBridge(grid [][]int) (ans int) {
n := len(grid)
dirs := []int{-1, 0, 1, 0, -1}
type pair struct{ i, j int }
q := []pair{}
var dfs func(int, int)
dfs = func(i, j int) {
grid[i][j] = 2
q = append(q, pair{i, j})
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 {
dfs(x, y)
}
}
}
for i, x := 0, 1; i < n && x == 1; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
dfs(i, j)
x = 0
break
}
}
}
for {
for i := len(q); i > 0; i-- {
p := q[0]
q = q[1:]
for k := 0; k < 4; k++ {
x, y := p.i+dirs[k], p.j+dirs[k+1]
if x >= 0 && x < n && y >= 0 && y < n {
if grid[x][y] == 1 {
return
}
if grid[x][y] == 0 {
grid[x][y] = 2
q = append(q, pair{x, y})
}
}
}
}
ans++
}
}
# Accepted solution for LeetCode #934: Shortest Bridge
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
def dfs(i, j):
q.append((i, j))
grid[i][j] = 2
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] == 1:
dfs(x, y)
n = len(grid)
dirs = (-1, 0, 1, 0, -1)
q = deque()
i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j])
dfs(i, j)
ans = 0
while 1:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n:
if grid[x][y] == 1:
return ans
if grid[x][y] == 0:
grid[x][y] = 2
q.append((x, y))
ans += 1
// Accepted solution for LeetCode #934: Shortest Bridge
struct Solution;
use std::collections::VecDeque;
impl Solution {
fn shortest_bridge(mut a: Vec<Vec<i32>>) -> i32 {
let n = a.len();
let m = a[0].len();
let mut queue: VecDeque<(usize, usize, i32)> = VecDeque::new();
let mut found = false;
for i in 0..n {
if found {
break;
}
for j in 0..m {
if a[i][j] == 1 {
Self::dfs(i, j, &mut queue, &mut a, n, m);
found = true;
break;
}
}
}
while let Some((i, j, d)) = queue.pop_front() {
match a[i][j] {
0 | 2 => {
a[i][j] = 3;
if i > 0 && a[i - 1][j] < 2 {
queue.push_back((i - 1, j, d + 1));
}
if j > 0 && a[i][j - 1] < 2 {
queue.push_back((i, j - 1, d + 1));
}
if i + 1 < n && a[i + 1][j] < 2 {
queue.push_back((i + 1, j, d + 1));
}
if j + 1 < m && a[i][j + 1] < 2 {
queue.push_back((i, j + 1, d + 1));
}
}
1 => {
return d - 1;
}
_ => {}
}
}
0
}
fn dfs(
i: usize,
j: usize,
queue: &mut VecDeque<(usize, usize, i32)>,
a: &mut Vec<Vec<i32>>,
n: usize,
m: usize,
) {
if a[i][j] == 1 {
a[i][j] = 2;
queue.push_back((i, j, 0));
if i > 0 {
Self::dfs(i - 1, j, queue, a, n, m);
}
if j > 0 {
Self::dfs(i, j - 1, queue, a, n, m);
}
if i + 1 < n {
Self::dfs(i + 1, j, queue, a, n, m);
}
if j + 1 < m {
Self::dfs(i, j + 1, queue, a, n, m);
}
}
}
}
#[test]
fn test() {
let a = vec_vec_i32![[0, 1], [1, 0]];
let res = 1;
assert_eq!(Solution::shortest_bridge(a), res);
let a = vec_vec_i32![[0, 1, 0], [0, 0, 0], [0, 0, 1]];
let res = 2;
assert_eq!(Solution::shortest_bridge(a), res);
let a = vec_vec_i32![
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
];
let res = 1;
assert_eq!(Solution::shortest_bridge(a), res);
}
// Accepted solution for LeetCode #934: Shortest Bridge
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #934: Shortest Bridge
// class Solution {
// private int[] dirs = {-1, 0, 1, 0, -1};
// private Deque<int[]> q = new ArrayDeque<>();
// private int[][] grid;
// private int n;
//
// public int shortestBridge(int[][] grid) {
// this.grid = grid;
// n = grid.length;
// for (int i = 0, x = 1; i < n && x == 1; ++i) {
// for (int j = 0; j < n; ++j) {
// if (grid[i][j] == 1) {
// dfs(i, j);
// x = 0;
// break;
// }
// }
// }
// int ans = 0;
// while (true) {
// for (int i = q.size(); i > 0; --i) {
// var p = q.pollFirst();
// for (int k = 0; k < 4; ++k) {
// int x = p[0] + dirs[k], y = p[1] + dirs[k + 1];
// if (x >= 0 && x < n && y >= 0 && y < n) {
// if (grid[x][y] == 1) {
// return ans;
// }
// if (grid[x][y] == 0) {
// grid[x][y] = 2;
// q.offer(new int[] {x, y});
// }
// }
// }
// }
// ++ans;
// }
// }
//
// private void dfs(int i, int j) {
// grid[i][j] = 2;
// q.offer(new int[] {i, j});
// for (int k = 0; k < 4; ++k) {
// int x = i + dirs[k], y = j + dirs[k + 1];
// if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1) {
// dfs(x, y);
// }
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.