diff --git a/63/step1.cpp b/63/step1.cpp new file mode 100644 index 0000000..97b82fe --- /dev/null +++ b/63/step1.cpp @@ -0,0 +1,38 @@ +//Time: 15:26 +// Space Complexity: O(m*n) +// Time Complexity: O(m*n) + +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int height = obstacleGrid.size(); + int width = obstacleGrid.front().size(); + vector> step_count(height, vector(width, 0)); + + if (obstacleGrid[0][0] == 1) { + return 0; + } + + step_count[0][0]=1; + + for (int row = 0; row < height; ++row) { + for (int col = 0; col < width; ++col) { + if (obstacleGrid[row][col] == 1) { + continue; + } + if (row == 0 && col == 0) { + continue; + } + int current_step_count = 0; + if (row > 0) { + current_step_count += step_count[row-1][col]; + } + if (col > 0) { + current_step_count += step_count[row][col-1]; + } + step_count[row][col] = current_step_count; + } + } + return step_count[height-1][width-1]; + } +}; diff --git a/63/step2.cpp b/63/step2.cpp new file mode 100644 index 0000000..7e4521b --- /dev/null +++ b/63/step2.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + if (obstacleGrid[0][0] == 1) { + return 0; + } + vector> pathCount(obstacleGrid.size(), vector(obstacleGrid[0].size(), 0)); + pathCount[0][0] = 1; + for (int i = 0; i < pathCount.size(); ++i) { + for (int j = 0; j < pathCount[0].size(); ++j) { + if (i == 0 && j == 0) { + continue; + } + if (obstacleGrid[i][j] == 1) { + continue; + } + if (i > 0) { + pathCount[i][j] += pathCount[i - 1][j]; + } + if (j > 0) { + pathCount[i][j] += pathCount[i][j - 1]; + } + } + } + return pathCount.back().back(); + } +}; diff --git a/63/step3.cpp b/63/step3.cpp new file mode 100644 index 0000000..cef577a --- /dev/null +++ b/63/step3.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + if (obstacleGrid[0][0] == 1) { return 0; } + if (obstacleGrid.back().back() == 1) { return 0; } + + vector> pathCounter(obstacleGrid.size(), vector(obstacleGrid[0].size(), 0)); + + pathCounter[0][0] = 1; + for (int y = 0; y < obstacleGrid.size(); ++y) { + for (int x = 0; x < obstacleGrid[0].size(); ++x) { + if (obstacleGrid[y][x] == 1) { + continue; + } + if (x > 0) { + pathCounter[y][x] += pathCounter[y][x - 1]; + } + if (y > 0) { + pathCounter[y][x] += pathCounter[y - 1][x]; + } + } + } + return pathCounter.back().back(); + } +};