LeetCode探索(161):934-最短的桥

98 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情

题目

给你一个大小为 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].length
  • 2 <= n <= 100
  • grid[i][j]01
  • grid 中恰有两个岛

思考

本题难度中等。

首先是读懂题意。给你一个大小为 n x n 的二元矩阵 grid ,其中 1 表示陆地,0 表示水域。你可以将任意数量的 0 变为 1 ,以使两座岛连接起来,变成 一座岛 。返回必须翻转的 0 的最小数目。

题目等价于求矩阵中两个岛的最短距离,这里我们使用广度优先搜索来找到矩阵中两个块的最短距离。

首先,我们找到 grid 中的一座岛,然后不断向外延伸一圈,直到到达另一座岛,延伸的圈数即为最短距离。广度优先搜索时,我们将已经遍历过的位置标记为 -1。我们得到第一座岛的位置集合后,记为 island,并将其位置全部标记为 -1。接着,我们从 island 中的所有位置开始进行广度优先搜索,当到达任意的 1 时,即表示搜索到了第二个岛,此时搜索的层数 step 就是答案。

问题:

  • 为什么queue中的数据不出现重复呢?

    因为往queue中存入坐标后,会将grid对应的原坐标标记为 -1,因此queue中的数据不会出现重复。

解答

方法一:广度优先搜索

/**
 * @param {number[][]} grid
 * @return {number}
 */
var shortestBridge = function (grid) {
  const n = grid.length;
  const dirs = [
    [-1, 0],
    [1, 0],
    [0, 1],
    [0, -1],
  ];
  // 第一座岛的位置集合
  const island = [];
  // 队列
  const queue = [];
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === 1) {
        queue.push([i, j]);
        // 将已经遍历过的位置标记为 -1
        grid[i][j] = -1;
        // 遍历得到第一座岛的位置集合 island,之后存入队列 queue 中
        while (queue.length !== 0) {
          const cell = queue.shift();
          let x = cell[0],
            y = cell[1];
          island.push(cell);
          for (let k = 0; k < 4; k++) {
            let nx = x + dirs[k][0];
            let ny = y + dirs[k][1];
            if (nx >= 0 && ny >= 0 && nx < n && ny < n && grid[nx][ny] == 1) {
              queue.push([nx, ny]);
              grid[nx][ny] = -1;
            }
          }
        }
        for (const cell of island) {
          queue.push(cell);
        }

        // 搜索的层数 step
        let step = 0;
        // 广度优先搜索
        while (queue.length !== 0) {
          const sz = queue.length;
          for (let k = 0; k < sz; k++) {
            const cell = queue.shift();
            let x = cell[0],
              y = cell[1];
            for (let d = 0; d < 4; d++) {
              let nx = x + dirs[d][0];
              let ny = y + dirs[d][1];
              if (nx >= 0 && ny >= 0 && nx < n && ny < n) {
                if (grid[nx][ny] === 0) {
                  // 记录水域的位置,并标记为 -1
                  queue.push([nx, ny]);
                  grid[nx][ny] = -1;
                } else if (grid[nx][ny] === 1) {
                  // 搜索到了第二个岛
                  return step;
                }
              }
            }
          }
          // 层数 +1
          step++;
        }
      }
    }
  }
  return 0;
};
// 执行用时:80 ms, 在所有 JavaScript 提交中击败了84.04%的用户
// 内存消耗:47.5 MB, 在所有 JavaScript 提交中击败了57.45%的用户
// 通过测试用例:97 / 97

复杂度分析:

  • 时间复杂度:O(n^2),其中 n 表示 grid 的行数,grid 的行数与列数相等。
  • 空间复杂度:O(n^2)。

参考