063 Unique Paths II

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?

Example:

Input:
[
[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

Note:

m and n will be at most 100.

解释下题目:

062的基础上加了点障碍物,仅此而已

1. 还是动态规划法

实际耗时:1ms

public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        //特殊情况判断
        if (0 == obstacleGrid.length) {
            return 0;
        }
        //赋予初值,需要注意如果遇到障碍,后面的就不用赋初值了(因为根本到不了)
        int[][] result = new int[obstacleGrid.length][obstacleGrid[0].length];
        for (int i = 0; i < obstacleGrid.length; i++) {
            if (obstacleGrid[i][0] == 1) {
                break;
            } else {
                result[i][0] = 1;
            }
        }

        for (int j = 0; j < obstacleGrid[0].length; j++) {
            if (obstacleGrid[0][j] == 1) {
                break;
            } else {
                result[0][j] = 1;
            }
        }

        //“递归”求解
        for (int i = 1; i < obstacleGrid.length; i++) {
            for (int j = 1; j < obstacleGrid[0].length; j++) {
                if (1 == obstacleGrid[i][j]) {
                    result[i][j] = 0;
                } else {
                    result[i][j] = result[i - 1][j] + result[i][j - 1];
                }
            }
        }
        return result[obstacleGrid.length - 1][obstacleGrid[0].length - 1];
    }

  思路:跟062几乎一模一样,只是加上了障碍物的判断,如果有障碍物说明走不通,那么在赋予初值的时候记得对障碍物下面的和障碍物右边的数进行处理,然后在进行动态规划的时候把数组的这个值置成0,方便之后的处理。

时间复杂度O(nm),n和m是二维数组的长宽
空间复杂度O(1)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • ​ 那年暑假的写生夏令营早早就定在了凤凰,一个说要去了好多年的古城, 终于找了个借口和一大帮小屁孩和小屁孩她妈跟着...
    焦糖布丁BG7阅读 1,679评论 0 2
  • 文/黄梅枝 张承宇看到小矮子神气十足的样子很窝火,他准备等小矮子走近了狠狠教训教训他,谁知还没等他出手,小矮子就惨...
    黄梅枝阅读 4,200评论 14 24
  • 这是个广阔的世界, 五彩缤纷; 这是个多彩的旅行, 危机四伏。 朝天门很远,岸很近, 风偷袭轮舵, 以为是上天在和...
    仁义RY阅读 2,860评论 0 2
  • 忙完手头上的事情,我匆忙的就从江南赶回东北老家看妈妈,一是她刚结束了第二段婚姻,二是她马上就要过57岁生日了...
    一莎一世界阅读 1,855评论 0 0

友情链接更多精彩内容