看到这个题目的时候想到的是通过深度优先搜索算法进行求解,找到每一条能够到达Finish的路径,并计数+1,最后得出的计数值即为解。
程序设计后提交对于部分测试用例超时,程序如下:
class Solution {
public:
int count = 0;
bool Flag[101][101];
void DFS(int N, int M, int x, int y,vector<vector<int>>& data)
{
if(Flag[x])[y])
return;
if(x == N-1 && y == M-1)
{
//if(N != 0)
count ++ ;
return;
}
if(x + 1 <= N - 1)
{
if(data[x+1][y] != 1)
DFS(N,M,x+1,y,data);
}
if(y + 1 <= M - 1 )
{
if(data[x][y + 1] != 1)
DFS(N,M,x,y + 1,data);
}
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
cout << obstacleGrid.size() << obstacleGrid[0].size() << endl;
if(obstacleGrid[0][0] != 1)
DFS(obstacleGrid.size(),obstacleGrid[0].size(),0,0,obstacleGrid);
return count;
}
};
修改为动态规划后,提交通过,结果及代码如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int N = obstacleGrid.size() ;
int M = obstacleGrid[0].size();
vector<vector<unsigned int>>dp(N,vector<unsigned int>(M));
if(obstacleGrid[0][0] != 1)
{
dp[0][0] = 1;
int i = 1;
while(i < N)
{
if(!obstacleGrid[i][0])
dp[i][0] = dp[i - 1][0];
//cout << "lie "<<i<<"="<<obstacleGrid[i][0]<<endl;
i++;
}
i = 1;
while(i < M)
{
if(!obstacleGrid[0][i])
dp[0][i] = dp[0][i - 1];
//cout << "hang "<<i<<"="<<obstacleGrid[0][i]<<endl;
i++;
}
for(i = 1;i<N;i++)
{
for(int j = 1;j<M;j++)
{
if(!obstacleGrid[i][j])
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
//cout <<dp[i][j]<<' ';
}
//cout << endl;
}
}
else
return 0 ;
return dp[obstacleGrid.size() - 1][obstacleGrid[0].size() - 1];
}
};