zoukankan      html  css  js  c++  java
  • 百度2015 在线笔试题(2)

    题目

    障碍物问题,类似LeetCode45题Jump Game II

    不同的是,此处约定从左下角走至右上角,每一步只能向右、向上或斜上方前进,另外所给矩阵中元素1代表无障碍,元素0代表有障碍;

    分析

    动态规划,与LeetCode45题Jump Game II采用相同的处理,注意 (i , j)的取值即可!

    程序

    #include <iostream>
    #include <cstdlib>
    #include <vector>
    
    using namespace std;
    
    //直接用非递归算法求解
    class Solution {
    public:
        int uniquePathsWithObstacles(vector<vector<int> >& obstacleGrid) {
    
            if (obstacleGrid.empty())
                return 0;
    
            int m = obstacleGrid.size();
            int n = obstacleGrid[0].size();
    
            vector<vector<int> > ret(m, vector<int>(n, 0));
    
            //矩阵最左列
            for (int i = m-1; i >= 0; i--)
            {
                //无障碍,则有一条路径,否则不通
                if (obstacleGrid[i][0] == 1)
                    ret[i][0] = 1;
                else
                    break;
            }//for
    
            //矩阵最底行
            for (int j = 0; j < n; j++)
            {
                //无障碍,则有一条路径,否则不通
                if (obstacleGrid[m-1][j] == 1)
                    ret[m-1][j] = 1;
                else
                    break;
            }//for
    
            //其余位置
            for (int i = m-2; i >= 0; i--)
            {
                for (int j = 1; j < n; j++)
                {
                    //当前位置为障碍,则到此处路径数为0
                    if (obstacleGrid[i][j] == 0)
                        ret[i][j] = 0;
                    else{
                        ret[i][j] = ret[i+1][j] + ret[i][j-1] + ret[i+1][j-1];
                    }//else
                }//for
            }//for
    
            return ret[0][n - 1];
        }//uniques
    
    };
    
    int main()
    {
        Solution s;
    
        vector<vector<int> > v = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } };
        //vector<vector<int> > v = { { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 } };
        cout << s.uniquePathsWithObstacles(v) << endl;
    
        system("pause");
    
        return 0;
    }
  • 相关阅读:
    计算机的几种命令行
    oracle体系结构
    数字档案馆建设指南及档案业务系统归档接口规范
    ERP系统归档
    oracle ITL(事务槽)的理解
    oracle表属性
    docker+httpd的安装
    访问GitLab的PostgreSQL数据库,查询、修改、替换等操作
    docker+rabbitmq的安装
    docker+elasticsearch的安装
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214853.html
Copyright © 2011-2022 走看看