https://oj.leetcode.com/problems/unique-paths-ii/

图的深搜,有障碍物,有的路径不通。

刚开始想的时候用组合数算,但是公式没有推导出来。

于是用了深搜,递归调用。

但是图最大是100*100,太大了,超时。考虑到在计算(2,1)和(1,2)都用到了(2,2),也就是说有了重复计算。于是记录这些中间的数据。

而有的地方因为有障碍物,所以得的路径值是0,这又要和没有计算做个区分,于是又加了些数据,标志是否已经计算过了。

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
if(obstacleGrid.size() == )
return ; int row = obstacleGrid.size();
int col = obstacleGrid[].size();
//the destination position unavailable
if(obstacleGrid[row-][col-] == || obstacleGrid[][] ==)
return ;
vector<vector<bool> > handled; //to mark if xy has handled
vector<vector<int> > tempRecord;
handled.resize(row);
tempRecord.resize(row);
for(int i = ;i<row;i++)
{
tempRecord[i].resize(col);
handled[i].resize(col);
for(int j = ;j<col;j++)
handled[i][j] = false; // all initialized false
} int ans = calcPath(obstacleGrid,,,row,col,tempRecord,handled); //no path
if(ans < )
ans = ;
return ans;
} int calcPath(vector<vector<int> > &grid ,int xPos, int yPos,int row,int col,vector<vector<int> > &tempRecord,vector<vector<bool> > &handled)
{
//destination
if(xPos == row - && yPos == col - )
return ;
//unhandle this position
if(tempRecord[xPos][yPos] == && handled[xPos][yPos] == false)
{
int ans = ;
if(xPos < row- && grid[xPos + ][yPos] ==)
if(handled[xPos+][yPos] == false)
ans = calcPath(grid,xPos+,yPos,row,col,tempRecord,handled);
else
ans = tempRecord[xPos+][yPos]; if(yPos < col - && grid[xPos][yPos+] == )
//unhandled
if(handled[xPos][yPos+] == false)
ans += calcPath(grid,xPos,yPos+,row,col,tempRecord,handled);
else
ans += tempRecord[xPos][yPos+]; tempRecord[xPos][yPos] = ans;
}
handled[xPos][yPos] = true;
return tempRecord[xPos][yPos];
}
};

最新文章

  1. arcgis地图数据集合
  2. MVC中Action的执行过程
  3. Java开发之JSP指令
  4. Filestream/Windows Share导致Alwayson Failover失败
  5. Hadoop 权威指南学习1 (主要框架)
  6. VC++遇到的错误汇集
  7. 批量update
  8. div嵌套引起的margin-top不起作用(转)
  9. Shell脚本,自动化发布tomcat项目【转】
  10. Linux入门基础知识
  11. When Startup Disk is Full
  12. [转][SerialPort]测试用例
  13. HTML5页面开发的基础性模板
  14. UI 自动化测试 Macaca测试框架 安装时遇到的log
  15. bzoj4025: 二分图 lct
  16. [UE4]OnComponentBeginOverlap.AddDynamic 的编译错误
  17. 最简单删除SQL Server中所有数据的方法(不用考虑表之间的约束条件,即主表与子表的关系)
  18. [leetcode] 4. Path Sum
  19. 十一.安装Redis
  20. 【Unity】publishing setting keystore作用

热门文章

  1. java解析多层嵌套json字符串
  2. leetcode-20-Dynamic Programming
  3. usb driver编写 (转)
  4. poj-2386 lake counting(搜索题)
  5. POJ:1185-炮兵阵地(状压dp入门)
  6. BFS、模拟:UVa1589/POJ4001/hdu4121-Xiangqi
  7. Linux学习-SRPM 的使用 : rpmbuild (Optional)
  8. Django 二——models(admin、ORM),一对一、一对多、多对多操作,all、values、value_list的对比
  9. Jquery+Ajax+asp.net+sqlserver-编写的通用邮件管理(源码)
  10. Leetcode36---&gt;Valid Sudoku(判断给定的数独是否有效)