diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 490b6b5c..6f405d6a 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -333,6 +333,60 @@ var uniquePathsWithObstacles = function(obstacleGrid) { }; ``` +C +```c +//初始化dp数组 +int **initDP(int m, int n, int** obstacleGrid) { + int **dp = (int**)malloc(sizeof(int*) * m); + int i, j; + //初始化每一行数组 + for(i = 0; i < m; ++i) { + dp[i] = (int*)malloc(sizeof(int) * n); + } + + //先将第一行第一列设为0 + for(i = 0; i < m; ++i) { + dp[i][0] = 0; + } + for(j = 0; j < n; ++j) { + dp[0][j] = 0; + } + + //若碰到障碍,之后的都走不了。退出循环 + for(i = 0; i < m; ++i) { + if(obstacleGrid[i][0]) { + break; + } + dp[i][0] = 1; + } + for(j = 0; j < n; ++j) { + if(obstacleGrid[0][j]) + break; + dp[0][j] = 1; + } + return dp; +} + +int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize, int* obstacleGridColSize){ + int m = obstacleGridSize, n = *obstacleGridColSize; + //初始化dp数组 + int **dp = initDP(m, n, obstacleGrid); + + int i, j; + for(i = 1; i < m; ++i) { + for(j = 1; j < n; ++j) { + //若当前i,j位置有障碍 + if(obstacleGrid[i][j]) + //路线不同 + dp[i][j] = 0; + else + dp[i][j] = dp[i-1][j] + dp[i][j-1]; + } + } + //返回最后终点的路径个数 + return dp[m-1][n-1]; +} +``` -----------------------