DP Topic 5 Different Paths||

topic:

Idea:

        The idea for this question  is the same as Different Paths |  The idea is different. The only difference is that there are obstacles. When initializing our two-dimensional dp array, we should pay attention to the fact that the robot can only move to the right and downward, so the first line is initialized. In the first column, when an obstacle block is encountered, the initial value is 0 at the back and 1 in front of the obstacle block. When the obstacle block is within the two-dimensional map, our dp position should skip the obstacle block, that is, the dp[][] obstacle block should be 0.

The code is explained in detail below:

int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
	// 获取地图大小
	int n = obstacleGrid.size();
	int m = obstacleGrid[0].size();
	
	// 定义dp数组
	int dp[200][200];
	memset(dp,0,sizeof dp);
	
	// dp数组初始化
	for(int i = 0;i < m;++i)
	{
		if(!obstacleGrid[0][i])
		{
			dp[0][i] = 1;
		}else break;
	}
	for(int i = 0;i < n;++i)
	{
		if(!obstacleGrid[i][0])
		{
			dp[i][0] = 1;
		}else break;
	}
	
	// 开始dp寻值
	for(int i = 1;i < n;++i)
	{
		for(int j = 1;j < m;++j)
		{
			// 如果遇到障碍块,则跳过dp
			if(obstacleGrid[i][j]) continue;
			
			// dp 递推公式
			dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
		}
	}
	// 返回结果
	return dp[n - 1][m - 1];
}

Last commit:

Guess you like

Origin blog.csdn.net/hacker_51/article/details/132896323