Conversation
| area_dict = defaultdict(int) | ||
| max_label = 0 | ||
|
|
||
| def dfs(p, q, dict, label): |
| for i in range(m): | ||
| for j in range(n): | ||
| if visited[i][j] == 0 and grid[i][j] == 1: | ||
| dfs(i, j, area_dict, max_label) |
There was a problem hiding this comment.
area_dictは引数で渡していますが、visitedはenclosing scopeからアクセスするのは一貫性がないように感じました。
| m, n = len(grid), len(grid[0]) | ||
| visited = [[0]*n for _ in range(m)] | ||
| max_area = 0 | ||
| area_dict = defaultdict(int) |
There was a problem hiding this comment.
確かにlabelをいちいちインクリメントして格納しておく必要はなかったですね...
| label_max = 0 | ||
|
|
||
| def dfs(p, q, dict, label): | ||
| nonlocal visited |
| area_dict = defaultdict(int) | ||
| max_label = 0 | ||
|
|
||
| def dfs(p, q, dict, label): |
There was a problem hiding this comment.
p, qをmatrixのインデックスとして使うのは珍しい気がします。i, jやrow, col、y, xが一般的だと思います。
| ``` | ||
|
|
||
|
|
||
| ## step3: |
There was a problem hiding this comment.
全部同じ方法で書き直すよりも、バリエーションを持たせても良さそうに感じました。visitedを使わない、iterative DFS/BFS、union findなど色々あるかと。
| dfs(i, j, area_dict, label_max) | ||
| label_max += 1 | ||
| visited[i][j] = 1 | ||
| if len(area_dict.values()) == 0: |
| def dfs(p, q, dict, label): | ||
| visited[p][q] = 1 | ||
| dict[label] += 1 | ||
| if p-1 >= 0 and visited[p-1][q] == 0 and grid[p-1][q] == 1: |
There was a problem hiding this comment.
下で言及ありますが、やや繰り返しがすぎるように感じました。8方向に繋がっている場合とかだと、どうするかを考えると良いかもしれません。
| class Solution: | ||
| def maxAreaOfIsland(self, grid: List[List[int]]) -> int: | ||
| m, n = len(grid), len(grid[0]) | ||
| visited = [[0]*n for _ in range(m)] |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
mt2324/leetcode#2 (comment)
| area_dict = defaultdict(int) | ||
| label_max = 0 | ||
|
|
||
| def dfs(p, q, dict, label): |
There was a problem hiding this comment.
関数名は動詞の原型または命令形から始まることが多いように思います。また、 dfs という単語は、関数の実装内容の詳細に示し過ぎているように思います。 traverse はいかがでしょうか?
There was a problem hiding this comment.
claudeに聞いてみると
traverse — グラフ・木を「巡る/たどる」という移動プロセスに焦点。汎用的で広く使われる。
explore — 「未知の領域を探索する」というニュアンスで、島問題との相性が少し強い。
traverse が特に自然に感じられる文脈は、戻り値を使わずに副作用(カウンタの更新など)で面積を記録するスタイルのときです。
面積を返すスタイルなら explore や countCells、副作用で記録するスタイルなら traverse が収まりよく感じます。
と来たので今回は副作用をもたらす関数として使ってるのでtraverseが良さそうですね。
問題:695. Max Area of Island
次の問題:https://leetcode.com/problems/word-ladder/description/
言語:Python