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

    将obstacle标记为-1,其余基本跟上一题一样。

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
     4         int m = obstacleGrid.size();
     5         int n = obstacleGrid[0].size();
     6         int i, j;
     7         for (i = 0; i < m; ++i) {
     8             for (j = 0; j < n; ++j) {
     9                 obstacleGrid[i][j] = -obstacleGrid[i][j];
    10             }
    11         }
    12         for (i = 0; i < m; ++i) {
    13             if (obstacleGrid[i][0] == -1) break;
    14             obstacleGrid[i][0] = 1;
    15         }
    16         for (j = 0; j < n; ++j) {
    17             if (obstacleGrid[0][j] == -1) break;
    18             obstacleGrid[0][j] = 1;
    19         }
    20         for (i = 1; i < m; ++i) {
    21             for (j = 1; j < n; ++j) {
    22                 if (obstacleGrid[i][j] == -1) continue;
    23                 obstacleGrid[i][j] += (obstacleGrid[i-1][j] == -1) ? 0 : obstacleGrid[i-1][j];
    24                 obstacleGrid[i][j] += (obstacleGrid[i][j-1] == -1) ? 0 : obstacleGrid[i][j-1];
    25             }
    26         }
    27         return (obstacleGrid[m-1][n-1] == -1) ? 0 : obstacleGrid[m-1][n-1];
    28     }
    29 };
  • 相关阅读:
    cast() 函数进行类型转换
    '+' 拼接字符串引起的小事故
    shell统计ip访问情况并分析访问日志
    Windows 环境上域名配置
    WebApi中Route的作用
    Postman测试WebApi使用总结
    C# VS2017新建WepApi
    C# 反射总结
    winform--同一个项目窗体复制
    winform TextBox设置透明
  • 原文地址:https://www.cnblogs.com/easonliu/p/3636668.html
Copyright © 2011-2022 走看看