【网格 dp】B001_LC_不同路径 II(注意边界)

一、题目描述

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

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.

输入:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右

二、题解

思路

由题意得,机器人只能向右或者向下走,那么在第 1 行和第 1 列,机器人只有一个选择:

  • 在第一行只能从左边的格子移动;
  • 在第一列只能从上方的格子移动。

第一个格子的值如果是 1,直接返回,如果是 0,那么设置为 1。随后,继续下列步骤:

方法一:dp

  • 定义状态
    • f [ i ] [ j ] f[i][j] f[i][j] 表示到达 (i, j) 的走法数量
  • 思考初始化:
    • f[0][0] = g[0][0] = 1 ? 0 : 1
  • 思考状态转移方程
    • 如果 g[i][j] = 0, f [ i ] [ j ] = f [ i − 1 ] [ j ] + f [ i ] [ j − 1 ] f[i][j] = f[i-1][j] + f[i][j-1] f[i][j]=f[i1][j]+f[i][j1]
    • 如果 g[i][j] = 1, f [ i ] [ j ] = 0 f[i][j] = 0 f[i][j]=0
  • 思考输出 f [ n ] [ m ] f[n][m] f[n][m]

这里额外判断了一下第一行和第一列…

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& g) {
        if (g[0][0])  return 0;
    	int n = g.size(), m = g[0].size();
    	vector<vector<int>> f(n+1, vector<int>(m+1));
    	f[1][1] = 1;
    	for (int j = 2; j <= m; j++) f[1][j] = g[0][j-1] == 0 ? f[1][j-1] : 0;
		for (int i = 2; i <= n; i++) f[i][1] = g[i-1][0] == 0 ? f[i-1][1] : 0;
		
		for (int i = 2; i <= n; i++)
		for (int j = 2; j <= m; j++) {
			if (g[i-1][j-1] == 0)
				f[i][j] = f[i-1][j] + f[i][j-1];
			else
				f[i][j] = 0;
		}
    	return f[n][m];
    }
};

复杂度分析

  • 时间复杂度: O ( n × m ) O(n × m) O(n×m)
  • 空间复杂度: O ( n × m ) O(n × m) O(n×m)

你可能感兴趣的:(#,网格,dp)