2
* @param {number[][]} grid12
var shortestBridge = function (grid) {14
const ROWS = grid.length;15
const COLS = grid[0].length;18
outer: for (let row = 0; row < ROWS; row++) {19
for (let col = 0; col < COLS; col++) {20
if (grid[row][col] == 1) {21
const stack = [[row, col]];22
while (stack.length) {23
const [r, c] = stack.pop();25
grid[r][c] = 2; // mark as visited.26
for (const dir of DIR) {27
const newRow = r + dir[0];28
const newCol = c + dir[1];29
if (newRow < 0 || newCol < 0 || newRow >= ROWS || newCol >= COLS)31
if (grid[newRow][newCol] != 1) continue;32
stack.push([newRow, newCol]);41
let size = que.length;42
for (let i = 0; i < size; i++) {43
const [row, col] = que.shift();44
for (const dir of DIR) {45
const newRow = row + dir[0];46
const newCol = col + dir[1];47
if (newRow < 0 || newCol < 0 || newRow >= ROWS || newCol >= COLS)49
if (grid[newRow][newCol] == 2) continue;50
if (grid[newRow][newCol] == 1) return steps;51
grid[newRow][newCol] = 2; // mark as visited.52
que.push([newRow, newCol]);