DAY24:leetcode #63 Unique Paths II

来源:互联网 发布:php仿qq聊天系统 编辑:程序博客网 时间:2024/06/03 20:57

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[  [0,0,0],  [0,1,0],  [0,0,0]]

The total number of unique paths is 2.

Note: m and n will be at most 100.

Subscribe to see which companies asked this question

class Solution(object):    def findPath(self, m, n):        if (m,n) in self.cache:            return self.cache[(m,n)]        m_step, n_step =0,0        if m < self.r_len and self.obstacleGrid[m + 1][n] == 0:            m_step = self.findPath(m + 1, n)        if n < self.c_len and self.obstacleGrid[m][n + 1] == 0:            n_step = self.findPath(m, n + 1)        self.cache[(m,n)] = m_step + n_step        return self.cache[(m,n)]    def uniquePathsWithObstacles(self, obstacleGrid):        """        :type obstacleGrid: List[List[int]]        :rtype: int        """        self.obstacleGrid = obstacleGrid        self.r_len = len(obstacleGrid) - 1        self.c_len = len(obstacleGrid[0]) - 1        self.cache = {(self.r_len, self.c_len): 1}         #起点或终点有阻碍则返回0        if obstacleGrid[self.r_len][self.c_len] or obstacleGrid[0][0]:            return 0        return self.findPath(0, 0)

相比于上一个算法,加入了向右和向下时的判断。

0 0
原创粉丝点击