【leetcode刷题笔记】Unique Paths II
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.
题解:和http://www.cnblogs.com/sunshineatnoon/p/3798167.html非常相似,要注意两点:
- 有障碍的地方能走到的方法数目是0;
- 初始化结果矩阵的时候,如果第一行(列)的某个位置有障碍,那么这一行(列)该元素后面所有的元素都是0,不能置为1;比如给定障碍矩阵[1,0,0],那么初始化以后的矩阵应该为[0,0,0],而不是[0,1,1],因为(0,0)处有障碍,那么该矩阵的任何位置都是无法到达的。
代码如下:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 int m = obstacleGrid.length; 4 int n = obstacleGrid[0].length; 5 if(m==0 && n == 0) 6 return 0; 7 8 int[][] PathNum = new int[m][n]; 9 for(int i = 0;i < m;i++) 10 if(obstacleGrid[i][0] != 1) 11 PathNum[i][0] = 1; 12 else 13 break; 14 for(int i = 0;i < n;i++) 15 if(obstacleGrid[0][i] != 1) 16 PathNum[0][i] = 1; 17 else 18 break; 19 20 for(int i = 1;i < m;i++) 21 for(int j = 1;j < n;j++){ 22 if(obstacleGrid[i][j] != 1) 23 PathNum[i][j] = PathNum[i-1][j]+PathNum[i][j-1]; 24 } 25 26 return PathNum[m-1][n-1]; 27 } 28 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了