From db2e2d2115b4606734340424cea2e6c326c4604b Mon Sep 17 00:00:00 2001 From: Ryohei Sato <130881456+Satorien@users.noreply.github.com> Date: Fri, 20 Jun 2025 10:01:57 +0900 Subject: [PATCH] Create 63. Unique Paths II.md --- Python3/63. Unique Paths II.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Python3/63. Unique Paths II.md diff --git a/Python3/63. Unique Paths II.md b/Python3/63. Unique Paths II.md new file mode 100644 index 0000000..08b28b3 --- /dev/null +++ b/Python3/63. Unique Paths II.md @@ -0,0 +1,76 @@ +## Step 1. Initial Solution + +- 基本的には前問のUnique Pathsと同じ考え方 + - 前の行を保持しておくことで縦方向に足していき、ループの中で横方向にも足していく +- 注意点としては + - 一行目から横方向に足していく必要があること + - 一列目はcontinueすること + +```python +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + num_rows = len(obstacleGrid) + num_cols = len(obstacleGrid[0]) + paths_to_row: list[int] = [1] + [0] * (num_cols-1) + for row in range(num_rows): + for col in range(num_cols): + if obstacleGrid[row][col] == 1: + paths_to_row[col] = 0 + continue + if col == 0: + continue + paths_to_row[col] += paths_to_row[col-1] + return paths_to_row[-1] + +``` + +### Complexity Analysis + +- 時間計算量:O(mn) +- 空間計算量:O(n) + +## Step 2. Alternatives + +- https://github.com/olsen-blue/Arai60/pull/34/files + - OBSTACLE = 1のように置いた方がマジックナンバー感はない + - pathsを二次元で書いている + - 直感的ではあるかもしれないが、不要なものを取っておくのは少し抵抗がある + - 異常入力のエラーハンドリング + - list[list[int]]であることは関数の引数で指定しているので、[[]]になっているケースだけ処理できれば良さそう + - `paths_to_row: list[int] = [1] + [0] * (num_cols-1)` の部分はエラーにならない + - どうやら後ろの整数が0以下の場合は空のリストを作るらしい + - https://github.com/python/cpython/blob/3.13/Objects/listobject.c#L800 +- https://github.com/sakupan102/arai60-practice/pull/35/files#r1615766614 + - リストの初期化はループの外の方が素直とのこと + - 同感だが、たまに自分もやりそうになるので気を付けたい + - https://github.com/sakupan102/arai60-practice/pull/35/files#diff-b6a3dbef984cd8394a3638997aca4fa3993fee36b17ae420ea28914e44b80104R44 + - 0で埋めてから0,0を1で初期化している + - こっちの方が素直なのか? + - 自分の感覚ではどっちが良いか分からなくなってしまった +- 違う言語でも読みやすいと感じた + - https://github.com/goto-untrapped/Arai60/pull/33/files#diff-79a50499a4e42f2697b078173d5edee715dee94830786cb69ffc4310e112ee63 + +## Step 3. Final Solution + +- 大枠の方針は同じままで少し変更を加えた程度 + +```python +OBSTACLE = 1 + +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + num_rows = len(obstacleGrid) + num_cols = len(obstacleGrid[0]) + paths_to_row = [1 if col == 0 else 0 for col in range(num_cols)] + + for row in range(num_rows): + for col in range(num_cols): + if obstacleGrid[row][col] == OBSTACLE: + paths_to_row[col] = 0 + continue + if col == 0: + continue + paths_to_row[col] += paths_to_row[col-1] + + return paths_to_row[-1] +```