-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
63. Unique Paths II #44
base: main
Are you sure you want to change the base?
Conversation
height, width = len(obstacleGrid), len(obstacleGrid[0]) | ||
|
||
ways = [ [0] * width for _ in range(height) ] | ||
for row in range(height): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
個人的には width と height に関する二重ループ一つにまとめ、ループの最内周で座標がグリッドの外にないかどうかをチェックするほうが好みです。ですが、この方法でもよいと思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
こういうことですか?
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
OBSTACLE = 1
height, width = len(obstacleGrid), len(obstacleGrid[0])
ways = [ [0] * width for _ in range(height) ]
for row in range(height):
for col in range(width):
if obstacleGrid[row][col] == OBSTACLE:
ways[row][col] = 0
continue
if row == 0 and col == 0:
ways[0][0] = 1
continue
if row == 0:
ways[0][col] = ways[0][col - 1]
continue
if col == 0:
ways[row][0] = ways[row - 1][0]
continue
ways[row][col] = ways[row - 1][col] + ways[row][col - 1]
return ways[height - 1][width - 1]
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
はい、その通りです。
また、 ways[row][col] = ways[row - 1][col] + ways[row][col - 1]
と、値を受け取る代わりに
if row + 1 < height:
ways[row + 1][col] += ways[row][col]
if col + 1 < width:
ways[row][col + 1] += ways[row][col]
のように、値を渡すようにしても良いと思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
値を渡すようにする方法だと、1つのセルに対する更新が複数のループにまたがるので、値を受け取る方が良いかなと思いました。
https://leetcode.com/problems/unique-paths-ii/