leetcode不同路径问题

205 阅读1分钟

1.从m,n的矩阵,从左上角走到右下角的所有可能的路径数

  • 动态规划
function uniquePaths(m: number, n: number): number {
  let res = [[]];
  for (let i = 0; i < n; i++) {
    res[0][i] = 1;
  }
  for (let i = 1; i < m; i++) {
    res[i] = [1];
    for (let j = 1; j < n; j++) {
      res[i][j] = res[i - 1][j] + res[i][j - 1];
    }
  }
  return res[m - 1][n - 1];
}

1.从m,n的矩阵,其中矩阵中值等于1表示障碍,求从左上角到右下角的所有路径数

  • 动态规划
function uniquePathsWithObstacles(obstacleGrid: number[][]): number {
  const m = obstacleGrid.length;
  const n = obstacleGrid[0].length;
  let res = [[0]];
  let temp = obstacleGrid?.[0]?.[0] === 1 ? 0 : 1;
  for (let i = 0; i < n; i++) {
    if (temp && obstacleGrid[0][i] === 1) temp = 0;
    res[0][i] = temp;
  }
  temp = obstacleGrid?.[0]?.[0] === 1 ? 0 : 1;
  for (let i = 1; i < m; i++) {
    if (temp && obstacleGrid[i][0] === 1) temp = 0;
    res[i] = [temp];
    for (let j = 1; j < n; j++) {
      res[i][j] = obstacleGrid[i][j] === 1 ? 0 : res[i - 1][j] + res[i][j - 1];
    }
  }
  return res[m - 1][n - 1];
}

1.从m,n的矩阵,其中矩阵中值等于1表示障碍,求从左上角到右下角的所有路径数

题目://leetcode 980-不同的路径 在二维网格 grid 上,有 4 种类型的方格:

  • 1 表示起始方格。且只有一个起始方格。
  • 2 表示结束方格,且只有一个结束方格。
  • 0 表示我们可以走过的空方格。
  • -1 表示我们无法跨越的障碍。 返回在四个方向(上、下、左、右)上行走时,从起始方格到结束方格的不同路径的数目。
//980-不同的路径
function uniquePathsIII(grid: number[][]): number {
  const START_FLAG = 1; //其实位置
  const CANPASS_FLAG = 0; //可以通过的位置
  const NOTPASS_FLAG = -1; //不能通过的位置
  const TARGET_FLAG = 2; //需要到达的位置
  const HASPASSED_FLAG = 4; //已经通过的位置

  let start_po = [];
  let allNeedPath = 0;

  function init() {
    grid.forEach((row, rowIndex) => {
      row.forEach((ele, j) => {
        if (ele === START_FLAG) {
          start_po = [rowIndex, j];
          allNeedPath++;
        } else if (ele === CANPASS_FLAG) {
          allNeedPath++;
        }
      });
    });
  }

  init();

  function sortPath(grid, nextStart, hasPassPos = 0) {
    const [i, j] = nextStart;
    let res = 0;
    if (i < 0 || i >= grid.length) {
      return 0;
    }
    if (j < 0 || j >= grid[0]?.length) {
      return 0;
    }
    if (hasPassPos >= allNeedPath && grid[i][j] === TARGET_FLAG) {
      return 1;
    }
    if (grid[i][j] !== CANPASS_FLAG && grid[i][j] !== START_FLAG) {
      return 0;
    }
    grid[i][j] = HASPASSED_FLAG;
    res += sortPath(grid, [i - 1, j], hasPassPos + 1);
    grid[i][j] = CANPASS_FLAG;

    grid[i][j] = HASPASSED_FLAG;
    res += sortPath(grid, [i + 1, j], hasPassPos + 1);
    grid[i][j] = CANPASS_FLAG;

    grid[i][j] = HASPASSED_FLAG;
    res += sortPath(grid, [i, j - 1], hasPassPos + 1);
    grid[i][j] = CANPASS_FLAG;

    grid[i][j] = HASPASSED_FLAG;
    res += sortPath(grid, [i, j + 1], hasPassPos + 1);
    grid[i][j] = CANPASS_FLAG;
    return res;
  }

  return sortPath(grid, start_po);
}

const xres = uniquePathsIII([
  [0, 1],
  [2, 0],
]);

运行效率击败100%