zoukankan      html  css  js  c++  java
  • 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.

    思路:动态规划

    本题不是特别的难,只需要判断下是否空格为1,如果为1,则sum为0,不是1的话,那么就和第一题一样。

    代码:

    class Solution {
    public:
    //https://leetcode.com/problems/unique-paths-ii/
        int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
            const int m=obstacleGrid.size(),n=obstacleGrid[0].size();
            if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1){
                return 0;
            }
            int sum[m][n];
            sum[0][0]=1;
            for(int i=1;i<n;i++){
                sum[0][i]=obstacleGrid[0][i]==0?sum[0][i-1]:0;
            }//如果等于1,直接为0;如果不为1,和前面相同
            for(int i=1;i<m;i++){
                sum[i][0]=obstacleGrid[i][0]==0?sum[i-1][0]:0;
            }
            
            for(int i=1;i<m;i++){
                for(int j=1;j<n;j++){
                    sum[i][j] = obstacleGrid[i][j]==0?(sum[i-1][j]+sum[i][j-1]):0;
                }
            }
            
            return sum[m-1][n-1];
        }
    };


  • 相关阅读:
    系统学习前端
    电脑上的图标拖不动
    js 给 input的value赋值
    js forEach的坑
    h5兼容性问题总结
    行内元素与块级元素
    百度搜索指令
    微信h5监听页面显示隐藏
    跨浏览器事件处理函数
    鼠标事件分析(onmouseenter、onmouseover、onmouseleave和onmouoseout的区别)
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519888.html
Copyright © 2011-2022 走看看