您的位置:首页 > 产品设计 > UI/UE

Unique Paths (第九周 动态规划)

2017-04-23 19:10 344 查看

Unique Paths (第九周 动态规划)

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).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

算法思路

(1)既然机器人每次只能向下或者向右走,那么说明每一个位置,都只能由它的上面和左边的位置到达。使用动态规划的思想,将全部位置上的到达方式初始化为1。然后从起始点开始,不断得更新到达该位置的方法数。

(2)状态转移方程为:

dp[i][j] = dp[i - 1][j] + dp[i][j - 1];

算法代码

class Solution {
public:
int uniquePaths(int m, int n) {
int dp[m]
;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
dp[i][j] = 1;
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++)
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
return dp[m - 1][n - 1];
}
};


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.

算法思路

(1)在上面那题的基础上,在地图上增加一些障碍,0是障碍,1可以通行。不过做法也类似。只不过一开始只将起始点初始化为零,然后从它开始,不断去更新附件的点的值,直到目标点。每个点的值还是和上题一样,是由左边和上面的值相加得到。但现在问题就是,这两个点可能是障碍,可能无法通行。

(2)所以状态转移方程和上面的一样,只不过需要加一个判断,判断上面和左边的点是否是障碍,不是的话,才加起来,如果是障碍,就无视前一个位置的值。

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int dp[m]
;
if(obstacleGrid[0][0] == 1)
return 0;

for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
dp[i][j] = 0;

dp[0][0] = 1;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++){
if(obstacleGrid[i][j] == 0){
if(i - 1 >= 0)
dp[i][j] += dp[i - 1][j];
if(j - 1 >= 0)
dp[i][j] += dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: