1.
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.
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> v(m, vector<int>(n, ));
int i, j;
for(i = ; i < m; i++)
{
for(j = ; j < n; j++)
{
if( == i || == j)
v[i][j] = ;
else
v[i][j] = v[i-][j] + v[i][j-];
}
}
return v[m-][n-];
}
};
2.
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.
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
if(m <= )
return ;
int n = obstacleGrid[].size();
if(n <= || obstacleGrid[][] == )
return ;
vector<vector<int>> v(m, vector<int>(n, ));
int i, j;
for(i = ; i < m; i++)
{
for(j = ; j < n; j++)
{
if(obstacleGrid[i][j] == )
v[i][j] = ;
else if( == i && j)
v[i][j] = v[][j-];
else if( == j && i)
v[i][j] = v[i-][];
else if(i && j)
v[i][j] = v[i-][j] + v[i][j-];
else
v[i][j] = ;
}
}
return v[m-][n-];
}
};
3.
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
int minPathSum(vector<vector<int> > &grid) {
if (grid.size()<=){
return ;
}
int i, j;
for(i=; i<grid.size(); i++){
for(j=; j<grid[i].size(); j++){
int top = i-< ? INT_MAX : grid[i-][j] ;
int left = j-< ? INT_MAX : grid[i][j-];
if (top==INT_MAX && left==INT_MAX){
continue;
}
grid[i][j] += (top < left? top: left);
}
}
return grid[grid.size()-][grid[].size()-];
}