|
| 1 | +/** |
| 2 | + * 934. Shortest Bridge |
| 3 | + * https://leetcode.com/problems/shortest-bridge/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an n x n binary matrix grid where 1 represents land and 0 represents water. |
| 7 | + * |
| 8 | + * An island is a 4-directionally connected group of 1's not connected to any other 1's. |
| 9 | + * There are exactly two islands in grid. |
| 10 | + * |
| 11 | + * You may change 0's to 1's to connect the two islands to form one island. |
| 12 | + * |
| 13 | + * Return the smallest number of 0's you must flip to connect the two islands. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} grid |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var shortestBridge = function(grid) { |
| 21 | + const n = grid.length; |
| 22 | + const queue = []; |
| 23 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 24 | + |
| 25 | + outer: for (let i = 0; i < n; i++) { |
| 26 | + for (let j = 0; j < n; j++) { |
| 27 | + if (grid[i][j] === 1) { |
| 28 | + findFirstIsland(i, j); |
| 29 | + break outer; |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + let distance = 0; |
| 35 | + while (queue.length) { |
| 36 | + const size = queue.length; |
| 37 | + for (let i = 0; i < size; i++) { |
| 38 | + const [row, col] = queue.shift(); |
| 39 | + for (const [dx, dy] of directions) { |
| 40 | + const newRow = row + dx; |
| 41 | + const newCol = col + dy; |
| 42 | + if (newRow < 0 || newRow >= n || newCol < 0 || newCol >= n |
| 43 | + || grid[newRow][newCol] === 2) continue; |
| 44 | + if (grid[newRow][newCol] === 1) return distance; |
| 45 | + grid[newRow][newCol] = 2; |
| 46 | + queue.push([newRow, newCol]); |
| 47 | + } |
| 48 | + } |
| 49 | + distance++; |
| 50 | + } |
| 51 | + |
| 52 | + return distance; |
| 53 | + |
| 54 | + function findFirstIsland(row, col) { |
| 55 | + if (row < 0 || row >= n || col < 0 || col >= n || grid[row][col] !== 1) return; |
| 56 | + grid[row][col] = 2; |
| 57 | + queue.push([row, col]); |
| 58 | + for (const [dx, dy] of directions) { |
| 59 | + findFirstIsland(row + dx, col + dy); |
| 60 | + } |
| 61 | + } |
| 62 | +}; |
0 commit comments