200. Number of Islands#36
Conversation
| ```python | ||
| class Solution: | ||
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| rows = len(grid) |
There was a problem hiding this comment.
rows だと、row の集まりのSequenceか何かだという印象が個人的にはあるので、num_rows などとした方が row の数であることが明確になるかもしれません。
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| rows = len(grid) | ||
| columns = len(grid[0]) | ||
| directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] |
There was a problem hiding this comment.
後から変更しない immutable な値であることを明示する目的で、tuple にしてもいいかもしれません。好みの範囲だと思いますが。
| visited = set() | ||
| num_islands = 0 | ||
|
|
||
| def dfs(r, c): |
There was a problem hiding this comment.
dfs という関数名はあまり好まれないように思います。DFSという内部でとっているアプローチを説明するよりも、何をするのか、何を入れて何が返ってくるのかわかりやすい関数名の方が呼び出し側からしたら扱いやすいと思います。
こちら参考リンクです https://discord.com/channels/1084280443945353267/1196472827457589338/1196612625916755968
There was a problem hiding this comment.
私自身もコメントもらっているので人のこと言えないのですが、sinkIslands()と命名している人がいて、直感的ですごくいいなって思ったことがあります。
| def dfs(r, c): | ||
| if not (0 <= r < rows and 0 <= c < columns): | ||
| return | ||
| if grid[r][c] != "1" or (r, c) in visited: |
There was a problem hiding this comment.
個人的な好みですが (個人的な好みばかりですみません、サンプルの一つとして) 一つの行で複数のことをするのは少し気を抜くと複雑になりすぎてしまうので、一行では基本的に一つのことがしたいです。この条件、「島ではない」と「訪問済み」を含んでいますが、早期リターンをするのは共通していますが、確認している条件は独立しているように思います。(好みの範囲だと思います。)
There was a problem hiding this comment.
私は、この条件は「未探索の島かどうか」を判定していると思ったので、あまり独立した印象を受けませんでした。ですので、分けなくてもいいのかなと思いました。
This problem: 200. Number of Islands
Next problem: 695. Max Area of Island