(grid)
| 6 | ]; |
| 7 | |
| 8 | const shortestBridge = (grid) => { |
| 9 | const rows = grid.length; |
| 10 | const cols = grid[0].length; |
| 11 | |
| 12 | let queue = []; |
| 13 | |
| 14 | const exploreIslandDFS = (row, col) => { |
| 15 | if ( |
| 16 | row < 0 || |
| 17 | row >= rows || |
| 18 | col < 0 || |
| 19 | col >= cols || |
| 20 | grid[row][col] !== 1 |
| 21 | ) { |
| 22 | return false; |
| 23 | } |
| 24 | |
| 25 | queue.push([row, col]); |
| 26 | grid[row][col] = 2; |
| 27 | |
| 28 | exploreIslandDFS(row - 1, col); |
| 29 | exploreIslandDFS(row + 1, col); |
| 30 | exploreIslandDFS(row, col - 1); |
| 31 | exploreIslandDFS(row, col + 1); |
| 32 | |
| 33 | return true; |
| 34 | }; |
| 35 | |
| 36 | const buildBridgeBFS = () => { |
| 37 | let distance = -1; |
| 38 | let currentQueue = []; |
| 39 | |
| 40 | while (queue.length) { |
| 41 | currentQueue = queue; |
| 42 | queue = []; |
| 43 | |
| 44 | for (let [row, col] of currentQueue) { |
| 45 | for (let [dx, dy] of DIRECTIONS) { |
| 46 | const nextRow = row + dx; |
| 47 | const nextCol = col + dy; |
| 48 | |
| 49 | if ( |
| 50 | nextRow >= 0 && |
| 51 | nextRow < rows && |
| 52 | nextCol >= 0 && |
| 53 | nextCol < cols && |
| 54 | grid[nextRow][nextCol] !== 2 |
| 55 | ) { |
| 56 | if (grid[nextRow][nextCol] === 1) { |
| 57 | return distance + 1; |
| 58 | } |
| 59 | |
| 60 | queue.push([nextRow, nextCol]); |
| 61 | grid[nextRow][nextCol] = 2; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 |
nothing calls this directly
no test coverage detected