Shortest Bridge
Problem statement
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 either0or1.- There are exactly two islands in
grid.
My solution
/**
* @param {number[][]} grid
* @return {number}
*/
var shortestBridge = function(grid) {
const queue = [];
let steps = 0;
const getDirs = (i, j) => [
[i + 1, j],
[i - 1, j],
[i, j + 1],
[i, j - 1]
]
function dfs(i, j) {
// console.log(grid.length, grid[0].length)
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] !== 1) {
return;
}
// console.log(i, j)
queue.push([i, j]);
grid[i][j] = "v";
for (const [newI, newJ] of getDirs(i, j)) {
// console.log(newI, newJ)
dfs(newI, newJ);
}
}
breakLoop: for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1) {
dfs(i, j)
break breakLoop;
}
}
}
while (queue.length) {
const size = queue.length;
for (let x = 0; x < size; x++) {
const [i, j] = queue.shift();
for (const [newI, newJ] of getDirs(i, j)) {
if (newI < 0 || newJ < 0 || newI >= grid.length || newJ >= grid[0].length || grid[newI][newJ] === "v") {
continue
}
if (grid[newI][newJ] === 1) {
return steps
}
queue.push([newI, newJ]);
grid[newI][newJ] = "v";
}
}
steps++;
}
// console.log(grid)
// console.log(queue)
// return steps;
};