标签:
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]; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4985570.html