Conversation
| if ( | ||
| not 0 <= next_row < NUM_ROW | ||
| or not 0 <= next_column < NUM_COLUMN | ||
| ): |
There was a problem hiding this comment.
選択肢の一つだと思いますが、
not (0 <= next_row < NUM_ROW and 0 <= next_column < NUM_COLUMN)
という書き方もあるかなと思いました。「not 範囲内である」という意図を表している気がします。
There was a problem hiding this comment.
こっちの方がわかりやすいですね!ありがとうございます
| NUM_ROW = len(grid) | ||
| NUM_COLUMN = len(grid[0]) |
There was a problem hiding this comment.
大文字が_で繋がっているこの形は定数に使うことが多いです。
https://peps.python.org/pep-0008/#descriptive-naming-styles
https://peps.python.org/pep-0008/#constants
There was a problem hiding this comment.
気持ちとしては定数のつもりで使っていました。
global constants以外は、local variable扱いでlower_with_underな書き方がいいんでしょうか?
https://google.github.io/styleguide/pyguide.html#3164-guidelines-derived-from-guidos-recommendations
| ```python | ||
| class Solution: | ||
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| NUM_ROW = len(grid) | ||
| NUM_COLUMN = len(grid[0]) | ||
| WATER = '0' | ||
|
|
||
| def traverse_island( | ||
| visited: List[List[bool]], | ||
| row: int, | ||
| column: int | ||
| ) -> None: | ||
| directions = ( | ||
| (1, 0), | ||
| (0, 1), | ||
| (-1, 0), | ||
| (0, -1), | ||
| ) | ||
| visited[row][column] = True | ||
| for delta_row, delta_column in directions: | ||
| next_row = row + delta_row | ||
| next_column = column + delta_column | ||
| if ( | ||
| not 0 <= next_row < NUM_ROW | ||
| or not 0 <= next_column < NUM_COLUMN | ||
| ): | ||
| continue | ||
| if grid[next_row][next_column] == WATER: | ||
| continue | ||
| if visited[next_row][next_column]: | ||
| continue | ||
| traverse_island(visited, next_row, next_column) | ||
|
|
||
| num_of_islands = 0 | ||
| visited = [[False] * NUM_COLUMN for _ in range(NUM_ROW)] | ||
| for row in range(NUM_ROW): | ||
| for column in range(NUM_COLUMN): | ||
| if grid[row][column] == WATER: | ||
| continue | ||
| if visited[row][column]: | ||
| continue | ||
| traverse_island(visited, row, column) | ||
| num_of_islands += 1 | ||
| return num_of_islands | ||
| ``` |
There was a problem hiding this comment.
良いのではないかと感じました。
敢えてコメントするとすると、好みかもしれませんが、全体的に縦長で目の上下の移動が発生することだけが、少し気になりました。
例えば、visitedとかですかね。最初の宣言時に「サイズの指定が、ない?」と不安になりました。(しっかり下でセットしてくださってましたので問題ないですが)
https://leetcode.com/problems/number-of-islands/description/