码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Paths & II

时间:2015-11-22 12:37:46      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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.

int uniquePaths(int m, int n) {
    int *v = (int *)malloc(n * sizeof(int));
    for(int i = 0; i < n; i++)
        v[i] = 1;
    for (int i = 1; i < m; ++i){
        for (int j = 1; j < n; ++j){
            v[j] += v[j - 1];
        }
    }
    return v[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.

 

int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize) {
    int i = 0;
    if(obstacleGrid[0][0] == 1)
        return 0;
//第一列初始化
    for(; i < obstacleGridRowSize; i++)
    {
        if(obstacleGrid[i][0] == 1)
            break;
        else
            obstacleGrid[i][0] = 1;
    }
    for(; i < obstacleGridRowSize; i++)
        obstacleGrid[i][0] = 0;
//第一行初始化        
    for(i = 1; i < obstacleGridColSize; i++)
    {
        if(obstacleGrid[0][i] == 1)
            break;
        else
            obstacleGrid[0][i] = 1;
    }
    for(; i < obstacleGridColSize; i++)
        obstacleGrid[0][i] = 0;
 //按照I的做法,把每步的值保存下来
    for(i = 1; i < obstacleGridRowSize; i++)
    {
        for(int j = 1; j < obstacleGridColSize; j++)
        {
            if(obstacleGrid[i][j] == 1)
                obstacleGrid[i][j] = 0;
            else
                obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
        }
    }
    return obstacleGrid[obstacleGridRowSize - 1][obstacleGridColSize - 1];
}

Unique Paths & II

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4985570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!