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.

 class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
int[][] dp = new int[rows][cols]; for(int i = 0; i < rows;i++){
for (int j = 0; j < cols ;j++){
if(obstacleGrid[i][j]==1)
dp[i][j] = 0;
else{
if (i==0&& j==0)
dp[i][j] = 1;
else if (i==0)
dp[i][j] = dp[i][j-1]; //边界 else if (j == 0)
dp[i][j] = dp[i-1][j];
else
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
return dp[rows-1][cols-1];
}
}
 class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
for(int i = 0; i < rows;i++){
for (int j = 0; j < cols ;j++){
if(obstacleGrid[i][j]==1)
obstacleGrid[i][j] = 0;
else if (i==0&& j==0)
obstacleGrid[i][j] = 1;
else if (i==0)
obstacleGrid[i][j] = obstacleGrid[i][j-1]*1; //边界,没有路径了,要么是0,要么是1 else if (j == 0)
obstacleGrid[i][j] = obstacleGrid[i-1][j]*1;
else
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
}
}
return obstacleGrid[rows-1][cols-1];
}
}

最新文章

  1. Angular.js 的初步认识
  2. 移动网站中,用canvas,svg比用图片好?
  3. SDR和DDR1/2/3全系列频率对照表
  4. 移动开发 android 入门开发 阶段视频
  5. HTTP权威指南----缓存
  6. 如何用Maven创建一个普通Java项目
  7. Esper系列(三)Context和Group by
  8. SQLSERVER 列名无效
  9. Windows 8 卡在正在检查更新
  10. 2.3、Android Studio使用Layout Editor设计UI
  11. iOS监听模式系列之关于delegate(代理,委托)的学习
  12. kv.go
  13. Oracle 触发器和序列的创建和使用 (自动增长列)
  14. 【CXF】com.sun.xml.internal.ws.fault.ServerSOAPFaultException: Client received SOAP Faul
  15. eclipse 反编译
  16. 20155326刘美岑 2016-2017-2 《Java程序设计》第5周学习总结
  17. 第二阶段Sprint冲刺会议6
  18. WebGL射线拾取模型——八叉树优化
  19. redisAPI整理
  20. jmeter中类型转换,字符串,转数字型或浮点型

热门文章

  1. hdu 1253:胜利大逃亡(基础广搜BFS)
  2. loadruner11 socket脚本-10053错误
  3. python3----练习......
  4. 40 个顶级 jQuery 图片、内容滑块和幻灯片
  5. SPOJ 375 QTREE
  6. 单台centos7.3 虚拟机实现主从复制和哨兵集群
  7. 170411、java Socket通信的简单例子(UDP)
  8. Python全栈day28(上下文管理)
  9. Socket连接何时需要断开
  10. [iOS微博项目 - 4.3] - 设置每条微博边框样式