zoukankan      html  css  js  c++  java
  • LeetCode OJ--Unique Paths II **

    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() == 0)
                return 0;
    
            int row = obstacleGrid.size();
            int col = obstacleGrid[0].size();
            //the destination position unavailable
            if(obstacleGrid[row-1][col-1] == 1 || obstacleGrid[0][0] ==1)
                return 0;
            vector<vector<bool> > handled; //to mark if xy has handled
            vector<vector<int> > tempRecord;
            handled.resize(row);
            tempRecord.resize(row);
            for(int i = 0;i<row;i++)
            {
                tempRecord[i].resize(col);
                handled[i].resize(col);
                for(int j = 0;j<col;j++)
                    handled[i][j] = false; // all initialized false
            }
    
            int ans = calcPath(obstacleGrid,0,0,row,col,tempRecord,handled);
            
            //no path
            if(ans < 0 )
                ans = 0;
            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 -1 && yPos == col -1 )
                return 1;
            //unhandle this position
            if(tempRecord[xPos][yPos] == 0 && handled[xPos][yPos] == false)
            {
                int ans = 0;
                if(xPos < row-1 && grid[xPos + 1][yPos] ==0)
                    if(handled[xPos+1][yPos] == false)
                        ans = calcPath(grid,xPos+1,yPos,row,col,tempRecord,handled);
                    else
                        ans = tempRecord[xPos+1][yPos];
                 
                if(yPos < col -1 && grid[xPos][yPos+1] == 0)
                    //unhandled
                    if(handled[xPos][yPos+1] == false)
                        ans += calcPath(grid,xPos,yPos+1,row,col,tempRecord,handled);
                    else   
                        ans += tempRecord[xPos][yPos+1];
    
                tempRecord[xPos][yPos] = ans;
            }
            handled[xPos][yPos] = true;
            return tempRecord[xPos][yPos];
        }
    };
  • 相关阅读:
    js学习总结----DOM中的节点和关系属性
    js学习总结----谷歌控制台详解
    ajax获取数据的形象比喻,助于理解记忆
    HTTP状态码对应
    jquery的on事件委托
    用 SwitchHosts设置hotst, 用法示例
    4、CommonChunkPlugin提取公共js-提取多个
    3、CommonChunkPlugin提取公共js-以提取一个jquery为例
    html-webpack-plugin
    2、extract-text-webpack-plugin提取Sass编译的Css
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3794167.html
Copyright © 2011-2022 走看看