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 };
  • 相关阅读:
    树(三)——自平衡二叉树(AVL)
    树(二)——二叉树
    10. IDENTITY属性使用小结
    09. 约束与索引的联系
    08. 删除重复&海量数据
    07. 分页写法小结
    06. 父子节点(树)遍历写法小结
    01. SQL Server 如何读写数据
    05. 取SQL分组中的某几行数据
    04. 字符串合并与拆分写法小结
  • 原文地址:https://www.cnblogs.com/easonliu/p/3636668.html
Copyright © 2011-2022 走看看