diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_139_unique_paths_ii.py b/src/my_project/interviews/top_150_questions_round_22/ex_139_unique_paths_ii.py new file mode 100644 index 00000000..e0bd97c1 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_139_unique_paths_ii.py @@ -0,0 +1,17 @@ +from typing import List + + +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m, n = len(obstacleGrid), len(obstacleGrid[0]) + if obstacleGrid[0][0] == 1 or obstacleGrid[m - 1][n - 1] == 1: + return 0 + dp = [0] * n + dp[0] = 1 + for row in range(m): + for col in range(n): + if obstacleGrid[row][col] == 1: + dp[col] = 0 + elif col > 0: + dp[col] += dp[col - 1] + return dp[n - 1] diff --git a/src/my_project/interviews_typescript/top_150_questions_round_1/ex_139_unique_paths_ii.ts b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_139_unique_paths_ii.ts new file mode 100644 index 00000000..d596dd4d --- /dev/null +++ b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_139_unique_paths_ii.ts @@ -0,0 +1,17 @@ +function uniquePathsWithObstacles(obstacleGrid: number[][]): number { + const m = obstacleGrid.length; + const n = obstacleGrid[0].length; + if (obstacleGrid[0][0] === 1 || obstacleGrid[m - 1][n - 1] === 1) return 0; + const dp: number[] = new Array(n).fill(0); + dp[0] = 1; + for (let row = 0; row < m; row++) { + for (let col = 0; col < n; col++) { + if (obstacleGrid[row][col] === 1) { + dp[col] = 0; + } else if (col > 0) { + dp[col] += dp[col - 1]; + } + } + } + return dp[n - 1]; +}; \ No newline at end of file diff --git a/tests/test_150_questions_round_22/test_139_unique_paths_ii_round_22.py b/tests/test_150_questions_round_22/test_139_unique_paths_ii_round_22.py new file mode 100644 index 00000000..30776fdf --- /dev/null +++ b/tests/test_150_questions_round_22/test_139_unique_paths_ii_round_22.py @@ -0,0 +1,30 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_22\ +.ex_139_unique_paths_ii import Solution + + +class UniquePathsIITestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + + def test_example_1(self): + self.assertEqual(2, self.solution.uniquePathsWithObstacles([[0,0,0],[0,1,0],[0,0,0]])) + + def test_example_2(self): + self.assertEqual(1, self.solution.uniquePathsWithObstacles([[0,1],[0,0]])) + + def test_obstacle_at_start(self): + self.assertEqual(0, self.solution.uniquePathsWithObstacles([[1,0],[0,0]])) + + def test_obstacle_at_end(self): + self.assertEqual(0, self.solution.uniquePathsWithObstacles([[0,0],[0,1]])) + + def test_single_cell_no_obstacle(self): + self.assertEqual(1, self.solution.uniquePathsWithObstacles([[0]])) + + def test_single_cell_obstacle(self): + self.assertEqual(0, self.solution.uniquePathsWithObstacles([[1]])) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file