Skip to content
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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open

63. Unique Paths II #44

wants to merge 8 commits into from

Conversation

hayashi-ay
Copy link
Owner

height, width = len(obstacleGrid), len(obstacleGrid[0])

ways = [ [0] * width for _ in range(height) ]
for row in range(height):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

個人的には width と height に関する二重ループ一つにまとめ、ループの最内周で座標がグリッドの外にないかどうかをチェックするほうが好みです。ですが、この方法でもよいと思います。

Copy link
Owner Author

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]

Copy link

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]

のように、値を渡すようにしても良いと思います。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

値を渡すようにする方法だと、1つのセルに対する更新が複数のループにまたがるので、値を受け取る方が良いかなと思いました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants