多源最短路径问题

188 阅读1分钟

01 矩阵【leetcode-542】

题目描述

给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

解题思路

  • 从源头出发,进行广度搜索遍历,找出到当前源头距离+1的位置
  • 依次进行遍历,最终找出所有的最短距离

运行效率

test.png

代码如下

function updateMatrix(mat: number[][]): number[][] {
  if (!mat.length) return null;

  const res = [];
  const queue: [number, number][] = [];

  function init() {
    mat.forEach((row, rowIndex) => {
      res[rowIndex] = [];
      row.forEach((ele, colIndex) => {
        if (ele === 0) {
          res[rowIndex][colIndex] = ele;
          queue.push([rowIndex, colIndex]);
        }
      });
    });
  }

  init();

  //进行广度搜索
  while (queue.length) {
    const [rowIndex, colIndex] = queue.shift();
    getPosRes(rowIndex - 1, colIndex, res[rowIndex][colIndex]);
    getPosRes(rowIndex + 1, colIndex, res[rowIndex][colIndex]);
    getPosRes(rowIndex, colIndex - 1, res[rowIndex][colIndex]);
    getPosRes(rowIndex, colIndex + 1, res[rowIndex][colIndex]);
  }

  //计算广度搜索的下一个位置
  function getPosRes(rowIndex: number, colIndex: number, tr: number) {
    if (
      rowIndex < 0 ||
      rowIndex >= mat.length ||
      colIndex < 0 ||
      colIndex >= mat[0].length
    ) {
      return;
    }
    if (res[rowIndex][colIndex] === undefined) {
      res[rowIndex][colIndex] = tr + 1;
      queue.push([rowIndex, colIndex]);
    }
  }

  return res;
}

const res = updateMatrix([
  [0, 1, 1, 1, 1, 0],
  [1, 1, 1, 1, 1, 0],
  [1, 1, 0, 1, 1, 0],
  [1, 1, 1, 1, 0, 0],
]);

debugger;