首页 > 代码库 > 每日算法之四十四:Unique Path(矩阵中不重复路径的数目)

每日算法之四十四:Unique Path(矩阵中不重复路径的数目)

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?

使用辅助矩阵,如何将辅助矩阵的规模减小是一个优化的选择:

    class Solution {
public:
    int uniquePaths(int m, int n) {
       int f[n];
       memset(f, 0, sizeof(int)*n);
       for(int i = 0; i < n; i++)
	       f[i] = 1;
      
       for(int i = 1; i < m; i++)
	       for(int j = 1; j < n; j++)
		       f[j] = f[j] + f[j-1];
       return f[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.

与上一题一样,只不过增加一个判断条件而已:

<span style="font-size:18px;">class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        int m = obstacleGrid.size();
	if(m <=0)
		return 0;
	int n = obstacleGrid[0].size();
	if(obstacleGrid[0][0] == 1)
		return 0;
	vector<int> maxpath(n,0);
	maxpath[0] = 1;

	for(int i = 0; i < m; i++)
		for(int j = 0; j < n; j++)
		{
			if(obstacleGrid[i][j] == 1)
				maxpath[j] = 0;
			else if(j > 0)
				maxpath[j] = maxpath[j] + maxpath[j-1];
		}
	return maxpath[n-1];
    }
};
</span>


每日算法之四十四:Unique Path(矩阵中不重复路径的数目)