LeetCode 63. Unique Paths II

本文探讨了在网格中寻找从起点到终点的路径数量问题,特别关注存在障碍的情况。文章给出了一个动态规划的解决方案,并进一步扩展到计算通过网格的最小成本路径的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

--- an extension of LeetCode 62. DP problem but need to pay more attention to the obstacle.

   int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
    if(obstacleGrid.size() == 0) return 0;
    if(obstacleGrid[0].size() == 0) return 0;
    
    int cols = obstacleGrid[0].size();
    int rows = obstacleGrid.size();

    vector< vector<int> > matrix(rows, vector<int>(cols, 0));
    
    for(int i = 0; i < cols; ++i) {
        if(obstacleGrid[0][i] != 1) {
            matrix[0][i] = 1;
        } else {break;}   // if obstacle, the left over path would be 0.
    } 
    for(int j = 0; j < rows; ++j) {
        if(obstacleGrid[j][0] != 1) {
            matrix[j][0] = 1;
        } else {break;} // if obstacle, the left over path would be 0.
    }

    for(int i = 1; i < rows; ++i) {
        for(int j = 1; j < cols; ++j) {
            if(obstacleGrid[i][j] != 1) {
                matrix[i][j] = matrix[i-1][j] + matrix[i][j-1];  // only if it is not an obstacle.
            } else {
                matrix[i][j] = 0;
            }
        }
    }
    return matrix[rows - 1][cols - 1];

 }


A variation: Find the minimum cost from first column to last column.

For example:

  [1, 2, 3]
  [2, 0, 0]
  [1, 0, 0]  the minimum cost is 1. The idea is to use DP. If there is only one column, it is easy. If there are two columns, there are three directions to go, up, down, right, thus, it need two sweeps.

int miniCost(vector< vector<int> >& matrix) {
  int m = matrix.size();
  int n = matrix[0].size();
  if(m == 0 || n == 0) return 0;
  vector<int> dp(m, 0);
  for(int i = 0; i < m; ++i) {
    dp[i] = matrix[i][n-1];
  }
  for(int i = n - 2; i >= 0; --i) {
    dp[0] += matrix[0][i];   // there is only one choice here.
    for(int j = 1; j < m; ++j) {
      dp[j] = min(dp[j-1], dp[j]) + matrix[j][i]; // go down or go left.
    }
    for(int j = m - 2; j >= 0; --j) {
      dp[j] = min(dp[j], dp[j + 1] + matrix[j][i]); // go up
    }
  }
  int mincost = INT_MAX;
  for(int i = 0; i < m; ++i) mincost = min(mincost, dp[0]);
  return mincost;
}

int main(void) {
  vector< vector<int> > matrix {
  {0, 1, 2},
  {0, 1, 2},
  {2, 0, 0}};
  cout << miniCost(matrix) << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值