λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 63 - Unique Paths II (Medium)

by HandHand 2021. 3. 4.

문제

LeetCode - 63번

풀이 κ³Όμ •

μ‹œμž‘ μ§€μ μ—μ„œ λͺ©ν‘œ 지점에 도달할 수 μžˆλŠ” 경우의 수λ₯Ό μ°ΎλŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
dp(x, y) λ₯Ό (x, y) μ—μ„œ 였λ₯Έμͺ½ ν•˜λ‹¨ λͺ¨μ„œλ¦¬μ— λ„λ‹¬ν•˜λŠ” 경우의 수라고 ν•œλ‹€λ©΄ λ‹€μŒκ³Ό 같은 점화식을 μ •μ˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

dp(x, y) = dp(x + 1, y) + dp(x, y + 1)


μ΄λ•Œ dp(x, y) μ—λŠ” μž₯애물이 μ—†μ–΄μ•Ό ν•˜λ©° 격자λ₯Ό λ²—μ–΄λ‚˜λ©΄ μ•ˆλ©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {number[][]} obstacleGrid
 * @return {number}
 */
var uniquePathsWithObstacles = function (obstacleGrid) {
  const m = obstacleGrid.length;
  const n = obstacleGrid[0].length;
  const memo = Array.from(Array(m), () => Array(n).fill(-1));

  function checkValidation(position) {
    if (
      position[0] < 0 ||
      position[0] >= m ||
      position[1] < 0 ||
      position[1] >= n
    )
      return false;
    return obstacleGrid[position[0]][position[1]] === 0;
  }

  function getPath(x, y) {
    if (x == m - 1 && y == n - 1) {
      return 1;
    }

    if (memo[x][y] !== -1) return memo[x][y];

    memo[x][y] = 0;

    const candidates = [
      [x, y + 1],
      [x + 1, y],
    ];
    for (const position of candidates) {
      if (checkValidation(position)) {
        memo[x][y] += getPath(position[0], position[1]);
      }
    }

    return memo[x][y];
  }

  if (obstacleGrid[0][0] === 1 || obstacleGrid[m - 1][n - 1] === 1) return 0;

  const answer = getPath(0, 0);

  return answer;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€