[LeetCode] 124: Unique Paths II

来源:互联网 发布:win7无法打开软件 编辑:程序博客网 时间:2024/06/11 23:22
[Problem]

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.


[Solution]

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0)return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();

// initial
int dp[m][n];
for(int i = 0; i < n; ++i){
if(i == 0){
if(obstacleGrid[0][i] == 1)
dp[0][i] = 0;
else
dp[0][i] = 1;
}
else if(obstacleGrid[0][i] == 1){
dp[0][i] = 0;
}
else{
dp[0][i] = dp[0][i-1];
}
}
for(int i = 0; i < m; ++i){
if(i == 0){
if(obstacleGrid[i][0] == 1)
dp[i][0] = 0;
else
dp[i][0] = 1;
}
else if(obstacleGrid[i][0] == 1){
dp[i][0] = 0;
}
else{
dp[i][0] = dp[i-1][0];
}
}

// dp
for(int i = 1; i < m; ++i){
for(int j = 1; j < n; ++j){
if(obstacleGrid[i][j] == 1){
dp[i][j] = 0;
}
else{
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 钱不够想买手机怎么办 安卓机屏幕密码忘了怎么办 屏幕解锁密码忘了怎么办 华为手机屏幕解锁密码忘了怎么办 oppo锁屏密码忘了怎么办 云助理密码忘了怎么办 购买方发票丢了怎么办 普票发票联丢失怎么办 唯品金融没还款怎么办 金点原子锁打不开了怎么办 87彩店注册不了怎么办 微店如果不退款怎么办 微信上微商被骗怎么办 微商代理不做了怎么办 微店拒收不退款怎么办 在微商买东西被骗怎么办 云集买家买东西不退款怎么办 微信红包密码忘记了怎么办 微信购物不退货怎么办 微信隐私设置无法添加怎么办 微信支付被限额怎么办 微信发现没有购物怎么办 微信转账钱被骗怎么办 玩连环夺宝输了好多钱怎么办 厘米秀换不了装怎么办 社保只缴纳两年怎么办 502盖子粘到手上怎么办 口红粘在盖子上怎么办 玫瑰手杖永久错过了怎么办 手指沾到502胶水怎么办 我退款了货到了怎么办 世纪天成账号被盗什么也没绑怎么办 韩国电话卡不想用怎么办2018 汽车没有年检交警抓到怎么办 ios软件未受信任怎么办 淘宝开店被管理了怎么办 微店网络异常025怎么办 商家给买家返款转错了怎么办 淘宝号限制下单怎么办 淘宝退货单号填错了怎么办 淘宝买家申请退款不退货怎么办