63. Unique Paths II

Description

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.

Solution

DP

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 
            || obstacleGrid[0].length == 0) {
            return 0;
        }
        
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) {
            return 0;
        }    
        
        int[][] path = new int[m][n];
        path[0][0] = 1;
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (obstacleGrid[i][j] != 0) {
                    path[i][j] = 0;
                } else {
                    if (i > 0) path[i][j] += path[i - 1][j];
                    if (j > 0) path[i][j] += path[i][j - 1];
                }
            }
        }
        
        return path[m - 1][n - 1];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.1 什么是自动引用计数#### 顾名思义,自动引用计数(ARC,Automatic Reference Cou...
    见哥哥长高了阅读 604评论 0 1
  • 这些天深圳的太阳有如夏天的热烈,在阳光下走上几步,就微微渗出汗来,路上不乏穿着短袖T恤的行人,身处南方的我们离冬天...
    文虫阅读 251评论 8 6
  • 在本该休息的晚上加班到12点,完成了一封很长的英语邮件,还有人耐心帮忙修改 有点累,但是有点欣慰 170715
    汪汪li阅读 259评论 0 0