본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 63. Unique Paths II

반응형

Unique Paths II

Difficulty: Medium


You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.

Return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The testcases are generated so that the answer will be less than or equal to 2 * 109.

 

Example 1:

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

Example 2:

Input: obstacleGrid = [[0,1],[0,0]]
Output: 1

 

Constraints:

  • m == obstacleGrid.length
  • n == obstacleGrid[i].length
  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1.

 

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        n, m = len(obstacleGrid), len(obstacleGrid[0])

        dp = [[0] * m for _ in range(n)]

        if obstacleGrid[0][0] == 0 :
            dp[0][0] = 1
        
        for i in range(1, n) :
            if obstacleGrid[i][0] == 0 :
                dp[i][0] = dp[i-1][0]
        
        for j in range(1, m) :
            if obstacleGrid[0][j] == 0 :
                dp[0][j] = dp[0][j-1]

        for i in range(1, n) :
            for j in range(1, m) :
                if obstacleGrid[i][j] == 0 :
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
                else :
                    dp[i][j] = 0

        return dp[-1][-1]

이 문제는 DP문제를 순수하게 내 손으로 풀었다. 

시행착오도 겁나 많이 밟아나갔다... 나중에 코테볼때 이러면 큰일나는데. 

일단 내가 어디서 실수 했는지 살펴보자. 

  1. 돌이 (0, 0) 혹은 (n-1, m-1) 좌표에, 즉 시작점과 도착점에 방해물이 있는지 고려하지 않았다. 
  2. 가장 첫번째 행, 열에 방해물이 있으면 이후 과정에서는 0으로 표기해야 하는 것을 고려하지 않았다. 

이 문제를 풀고나서 점화식에 대해서 다시 생각할 수 있게 되었고, 왜 DP 문제인가를 알 수 있었다. 

  1. 내부 값이 모두 0인 DP 테이블을 생성.
  2. 시작지점에서 방해물이 있는지 체크. 없으면 1, 있으면 0 => 결국 0이다. 
  3. 초기값 설정을 한다. 
    1. 1행을 지나면서 이전 칸이 1이면 현재 칸도 1
    2. 1열을 지나면서 이전 칸이 1이면 현재 칸도 1
  4. 이제 이중 for loop를 돌면서 현재 칸에 올 수 있는 가능성인 (i-1, j) 과 (i, j-1)칸의 수를 더해간다. 이것을 반복...

 

반응형