934. 最短的桥
给你一个大小为 n x n 的二元矩阵 grid ,其中 1 表示陆地,0 表示水域。
岛 是由四面相连的 1 形成的一个最大组,即不会与非组内的任何其他 1 相连。grid 中 恰好存在两座岛 。
你可以将任意数量的 0 变为 1 ,以使两座岛连接起来,变成 一座岛 。
返回必须翻转的 0 的最小数目。
示例 1:
输入: grid = [[0,1],[1,0]]
输出: 1
示例 2:
输入: grid = [[0,1,0],[0,0,0],[0,0,1]]
输出: 2
示例 3:
输入: 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]]
输出: 1
提示:
n == grid.length == grid[i].length2 <= n <= 100grid[i][j]为0或1grid中恰有两个岛
/**
* @param {number[][]} grid
* @return {number}
*/
var shortestBridge = function(grid) {
const n = grid.length;
// 首选DFS搜索第一个岛屿,并填为2进行区分,搜索同时岛屿周围的第一层0,进入队列
// 队列的每一项是一个[x, y, 层]
const queue = [];
let find = false;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
dfs(grid, i, j, queue);
find = true;
break;
}
}
if (find) {
break;
}
}
while (queue.length) {
const [x, y, h] = queue.shift();
if ((x - 1 >= 0 && grid[x - 1][y] === 1) ||
(x + 1 < n && grid[x + 1][y] === 1) ||
(y - 1 >= 0 && grid[x][y - 1] === 1) ||
(y + 1 < n && grid[x][y + 1] === 1)) {
return h;
}
if (x - 1 >= 0 && grid[x - 1][y] === 0) {
queue.push([x - 1, y, h + 1]);
grid[x - 1][y] = 2;
}
if (x + 1 < n && grid[x + 1][y] === 0) {
queue.push([x + 1, y, h + 1]);
grid[x + 1][y] = 2;
}
if (y - 1 < n && grid[x][y - 1] === 0) {
queue.push([x, y - 1, h + 1]);
grid[x][y - 1] = 2;
}
if (y + 1 < n && grid[x][y + 1] === 0) {
queue.push([x, y + 1, h + 1]);
grid[x][y + 1] = 2;
}
}
};
function dfs(grid, x, y, queue) {
grid[x][y] = 2;
if (x - 1 >= 0) {
if (grid[x - 1][y] === 1) {
dfs(grid, x - 1, y, queue);
} else if (grid[x - 1][y] === 0){
queue.push([x - 1, y, 1]);
grid[x - 1][y] = 2;
}
}
if (x + 1 < grid.length) {
if (grid[x + 1][y] === 1) {
dfs(grid, x + 1, y, queue);
} else if (grid[x + 1][y] === 0) {
queue.push([x + 1, y, 1]);
grid[x + 1][y] = 2;
}
}
if (y - 1 >= 0) {
if (grid[x][y - 1] === 1) {
dfs(grid, x, y - 1, queue);
} else if (grid[x][y - 1] === 0) {
queue.push([x, y - 1, 1]);
grid[x][y - 1] = 2;
}
}
if (y + 1 < grid.length) {
if (grid[x][y + 1] === 1) {
dfs(grid, x, y + 1, queue);
} else if (grid[x][y + 1] === 0) {
queue.push([x, y + 1, 1]);
grid[x][y + 1] = 2;
}
}
}