200. Number of Islands - #17
Conversation
| - 考えたこと | ||
| - gemini に聞きながら完成させた。 | ||
| - M と N の二重ループの中でさらに stack を使って隣接する LAND を全て WATER に破壊的変更をする形で DFS をする。 | ||
| - イメージで考えると、島の探索隊がいるとして、島の一部を見つけ次第、見つけたという記録をつけて、引き継ぎしながら**その島全体を海に沈める**。そしてまた次の人に引き継ぐ。島が見つからなければどんどん次の人に引き継いでいく。イメージで考えるとなかなかすごいことしてるな、この解法。笑 |
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| height = len(grid) | ||
| width = len(grid[0]) | ||
| visited = [[False] * width for _ in range(height)] |
There was a problem hiding this comment.
個人的にはこういう時 set で visited を作ることが多いのですが、ハッシュ値の計算がない分2重配列で持つのも良さそうですね
There was a problem hiding this comment.
ありがとうございます。確かにハッシュ値の計算がないのは input がかなり大きくなってきた時などに効いてきそうですね。
ちなみに、次の問題で、visited は list よりも set の方が 座標を保持する lands_to_visit とより対になるように見えて好みと思うようになりました。
https://github.com/kazizi55/coding-challenges/pull/18/changes#diff-63ea722117ed2338f5a398092eca978801bad4637318cf2eb1166a223863a409R310-R312
| WATER = "0" | ||
| LAND = "1" |
There was a problem hiding this comment.
より大掛かりなプログラムになると Enum で持つということも選択肢になるんでしょうか
There was a problem hiding this comment.
ありがとうございます。
同意です。
また、状態遷移をより明示したい場合などにも Enum が有効だと今は思うようになりました。
#14 (comment)
| ] | ||
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| num_islands = 0 | ||
| rows = len(grid) |
There was a problem hiding this comment.
rows という単語からは、行の情報が格納されているリストというニュアンスを感じます。自分なら num_rows と名付けると思います。
There was a problem hiding this comment.
ありがとうございます。
言われてみればおっしゃる通りですね。以降は len であることを変数名に含めようと思います。
| continue | ||
| num_islands += 1 | ||
| stack = [(r, c)] | ||
| grid[r][c] = self.WATER |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
Hiroto-Iizuka/coding_practice#17 (comment)
There was a problem hiding this comment.
ありがとうございます。
呼び出し側の立場から見ると、渡した値が関数内部で意図せず変更されると驚かれる可能性があります。
練習の一環として入力変更の解法も書いていたのですが、呼び出し側の気持ちを考えると変更する旨を関数名やコメントで明示すべきだったと思い直しました。以降はそのようにしていこうと思います。
| num_islands += 1 | ||
| stack = [(r, c)] | ||
| grid[r][c] = self.WATER | ||
| while len(stack) > 0: |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
mamo3gr/arai60#6 (comment)
There was a problem hiding this comment.
ありがとうございます。以降実践していきます。
PEP8 にも同じルールがあるのですね。
For sequences, (strings, lists, tuples), use the fact that empty sequences are false
https://leetcode.com/problems/number-of-islands/description/
Next: https://leetcode.com/problems/max-area-of-island/description/