Skip to content

200. Number of Islands#36

Open
hiro111208 wants to merge 1 commit into
mainfrom
200-number-of-islands
Open

200. Number of Islands#36
hiro111208 wants to merge 1 commit into
mainfrom
200-number-of-islands

Conversation

@hiro111208
Copy link
Copy Markdown
Owner

This problem: 200. Number of Islands

Next problem: 695. Max Area of Island

```python
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows = len(grid)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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]]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

後から変更しない immutable な値であることを明示する目的で、tuple にしてもいいかもしれません。好みの範囲だと思いますが。

visited = set()
num_islands = 0

def dfs(r, c):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dfs という関数名はあまり好まれないように思います。DFSという内部でとっているアプローチを説明するよりも、何をするのか、何を入れて何が返ってくるのかわかりやすい関数名の方が呼び出し側からしたら扱いやすいと思います。
こちら参考リンクです https://discord.com/channels/1084280443945353267/1196472827457589338/1196612625916755968

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私自身もコメントもらっているので人のこと言えないのですが、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:
Copy link
Copy Markdown

@huyfififi huyfififi May 26, 2026

Choose a reason for hiding this comment

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

個人的な好みですが (個人的な好みばかりですみません、サンプルの一つとして) 一つの行で複数のことをするのは少し気を抜くと複雑になりすぎてしまうので、一行では基本的に一つのことがしたいです。この条件、「島ではない」と「訪問済み」を含んでいますが、早期リターンをするのは共通していますが、確認している条件は独立しているように思います。(好みの範囲だと思います。)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私は、この条件は「未探索の島かどうか」を判定していると思ったので、あまり独立した印象を受けませんでした。ですので、分けなくてもいいのかなと思いました。

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.

4 participants