Conversation
695_max_area_of_island/step2.py
Outdated
|
|
||
| class Solution: | ||
| def maxAreaOfIsland(self, grid: List[List[int]]) -> int: | ||
| water = 0 |
There was a problem hiding this comment.
定数は他の変数と区別する意味でも大文字が良いと思います。
https://google.github.io/styleguide/pyguide.html#3164-guidelines-derived-from-guidos-recommendations
695_max_area_of_island/step2.py
Outdated
| width = len(grid[0]) | ||
| height = len(grid) |
There was a problem hiding this comment.
これは好み?アクセスする順番は len(grid), len(grid[0])の順番が自然な気がします。
695_max_area_of_island/step2.py
Outdated
| height = len(grid) | ||
|
|
||
| def calc_area(x: int, y: int) -> int: | ||
| if x >= width or 0 > x or y >= height or 0 > y or visited[y][x] or grid[y][x] == water: |
There was a problem hiding this comment.
pythonは比較演算子をchainできるので、not (0 <= x < width)とした方が分かりやすいように思います。
695_max_area_of_island/step2.py
Outdated
| max_area = 0 | ||
| for y in range(height): | ||
| for x in range(width): | ||
| visited = [[False] * width for _ in range(height)] |
There was a problem hiding this comment.
visitedは2重ループの外で定義するのが良いと思います。今の処理だと一度訪れたislandについても次のループで訪れていると思います。
| def find(self, x): | ||
| if self.parents[x] == x: | ||
| return x | ||
| else: |
| x = self.find(x) | ||
| y = self.find(y) |
There was a problem hiding this comment.
変数名をもう少し工夫した方が良いと思います。あと引数を使い回しているのも気になりました。
There was a problem hiding this comment.
target1, target2のようにしてみました。hayashiさんのコードではnodeという単語を使っているんですね。union-findがグラフになっているという感覚があまりなくてnodeが出てこなかったです。
| if grid[y][x] == land: | ||
| areas[uf.find(to_1d(x, y))] += 1 | ||
|
|
||
| return max([0, *areas.values()]) |
There was a problem hiding this comment.
こちらの方が自然ですかね? max(areas.values(), default=0)
個人的にはif文を使ってあげるので良いと思います。
There was a problem hiding this comment.
ありがとうございます。maxにdefaultやkeyを渡せるんですね。
指摘いただいて気づいたのですが、自分の好みとして今回のareasのkeyが無い場合のように相対的に珍しいケースのためにコードを長くしたくないという気持ちがありそうです。
| def to_1d(x, y): | ||
| return width * y + x | ||
|
|
||
| def union_connected_lands(x, y): |
There was a problem hiding this comment.
条件式が長いのが原因かなと思い、is_landとare_same_groupという関数を切り出してみました。
695_max_area_of_island/step1.py
Outdated
| area = 0 | ||
| visited = [[False] * width for _ in range(height)] | ||
|
|
||
| def search_land(x: int, y: int): |
There was a problem hiding this comment.
個人的には nonlocal 好きではないので、
area = 1
area += search_land()
area += search_land()
area += search_land()
area += search_land()
return area
としたいですね。
問題
https://leetcode.com/problems/max-area-of-island/description/
参考にしたDiscordのコメント
https://discord.com/channels/1084280443945353267/1200089668901937312/1211642725594824704
https://discord.com/channels/1084280443945353267/1183683738635346001/1195391359884988470