200.number of islands#17
Conversation
| }; | ||
| ``` | ||
|
|
||
| こちらは空間計算量もO(NM)になる。DFSはO(1)になるから問題の性質上走査するのでDFSが望ましいと思う。 |
There was a problem hiding this comment.
レビューありがとうございます。
DFSの方が空間計算量は節約できると思っていましたがすべてが島の場合を考えると再帰がNM回回るのでその分のメモリが保存され違いますね。
空間計算量はどちらも変わらずO(NM)でした。
| while (!islands.empty()) { | ||
| auto [row, column] = islands.front(); | ||
| islands.pop(); | ||
| for (int i = 0; i < 4; i++) { |
There was a problem hiding this comment.
i < 4ではなく、i < directions.size()が良いと思います。
| 参考:https://github.com/attractal/leetcode/pull/8/changes | ||
|
|
||
| 方法としては | ||
| 1.m行n列のbool配列visitedを作る。falseで初期化して上陸したらtrueにする。 |
There was a problem hiding this comment.
一応ですが、visitedは幅優先探索のためではなく、入力を破壊しない方法の一つとして導入されていますね。
There was a problem hiding this comment.
なるほど、確かに破壊ありならvisitedを使わずに島を沈没させる方向でも書けますね。
役割分担に気づいていませんでした。ありがとうございます。
| 参考:https://leetcode.com/problems/number-of-islands/description/comments/1570785/ | ||
|
|
||
| やり方としては | ||
| 1.visit関数をラムダ式でnumIslands関数の中に書く |
There was a problem hiding this comment.
自分でも調べてみようと思うのですが、
private関数を使わずにラムダ式を使う利点はあったりしますか?
There was a problem hiding this comment.
visit関数でgridを直接処理に使いたいのですがそれをprivateに書くと引数が一つ増えるので関数内でラムダ式を使用しました。
| public: | ||
| int numIslands(vector<vector<char>>& grid) { | ||
| auto visit = [&](auto& self, int x, int y) -> void { | ||
| if (0 <= x && x < grid[0].size() && 0 <= y && y < grid.size() && |
There was a problem hiding this comment.
条件式が長すぎるように感じるので、別のif文に分けるなどしてもいいですね
There was a problem hiding this comment.
レビューありがとうございます。
'1'の判定を分けるのがよさそうです。
| int rows = grid.size(); | ||
| int columns = grid[0].size(); |
There was a problem hiding this comment.
num_rows, num_cols とすると、より行「数」という意味が伝わりやすいと思います
| } | ||
| } | ||
| }; | ||
| for (int m = 0; m < grid.size(); m++) { |
There was a problem hiding this comment.
「行」を表す変数で、row, x, m などの異なる名前が付いているので、統一した方がいいかなと思いました
There was a problem hiding this comment.
ありがとうございます。
確かにrow,columnで統一したほうがいいですね。
This problem: https://leetcode.com/problems/number-of-islands/
Next problem: https://leetcode.com/problems/max-area-of-island/description/