200. Number of Islands#17
Conversation
tNita
commented
Apr 11, 2026
- この問題:Number of Islands
- 次の問題:Max Area of Island
| def is_inside_grid(i: int, j: int) -> bool: | ||
| return 0 <= i < height and 0 <= j < width | ||
|
|
||
| def visit_island(start: tuple[int, int]) -> None: |
There was a problem hiding this comment.
上で言及されていましたが、この関数の名前はvisit_islandよりもexplore_islandの方が実態を捉えていると思いました。
There was a problem hiding this comment.
ご指摘ありがとうざいます。確かにそうですね。
色々みていくうちに忘れてしまっていました。。。
| island_count = 0 | ||
| rows = len(grid) | ||
| columns = len(grid[0]) | ||
| visited = [ [False] * columns for _ in range(rows) ] |
There was a problem hiding this comment.
[] のすぐ内側にはスペースを空けないことが多いと思います。
参考までにスタイルガイドへのリンクを共有いたします。
https://google.github.io/styleguide/pyguide.html#36-whitespace
No whitespace inside parentheses, brackets or braces.
なお、このスタイルガイドは“唯一の正解”というわけではなく、数あるガイドラインの一つに過ぎません。チームによって重視される書き方や慣習も異なります。そのため、ご自身の中に基準を持ちつつも、最終的にはチームの一般的な書き方に合わせることをお勧めします。
There was a problem hiding this comment.
なるほどです。参考になりました。ありがとうございます。
| columns = len(grid[0]) | ||
| visited = [ [False] * columns for _ in range(rows) ] | ||
|
|
||
| def visit_island(current_i: int, current_j: int) -> None: |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
mamo3gr/arai60#16 (comment)
There was a problem hiding this comment.
(x, y) (r, c) (row, col) (row, column) などのほうが自然に感じます。 grid の添え字として [r][c] の順番でアクセスできるるよう、 (r, c) を使ってはいかがでしょうか?
確かに、row, columnの方が自然ですね。ありがとうございます。
| visited.add(land) | ||
| for direction in [[1, 0], [-1, 0], [0, 1], [0, -1]]: | ||
| neighbor = (land[0] + direction[0], land[1] + direction[1]) | ||
| if neighbor not in visited \ |
There was a problem hiding this comment.
適宜分割して early return したほうが読みやすくなると思いました。
if neighbor in visited:
continue
if not (0 <= neighbor[0] < len(grid) and 0 <= neighbor[1] < len(grid[0])):
continue
if grid[neighbor[0]][neighbor[1]] == "0":
continue
land_queue.append(neighbor)自分は空行を入れ、処理の区切れ目を視覚的に分かりやすくする派なのですが、趣味の範囲かもしれません。この辺りはチームの平均的な書き方に合わせることをお勧めいたします。
There was a problem hiding this comment.
承知いたしました。
適宜分割して early return したほうが読みやすくなると思いました。
continueが繰り返すものの、読みやすさでいうと early returnの方が良いですね。