Conversation
| if grid[row][col] == WATER: | ||
| return 0 | ||
| grid[row][col] = WATER | ||
| num_of_lands = 1 |
There was a problem hiding this comment.
問題文中に land という単語が登場しておらず、違和感を覚えました。問題文中に登場する area を使用するのはいかがでしょうか?
There was a problem hiding this comment.
An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.)
一応問題文中にもlandという単語はあるのですが、areaの方が良さそうです。
| class Solution: | ||
| def maxAreaOfIsland(self, grid: List[List[int]]) -> int: | ||
| def count_num_of_lands_while_removing(row, col): | ||
| if not (0 <= row < height and 0 <= col < width): |
There was a problem hiding this comment.
LAND・WATER・height・width の定義が下のほうに書かれており、定義を確かめるため視線を上下に移動させる必要がありました。視線を上から下に移動するだけでコードが読めるよう、定義は使用箇所より上に書いたほうが良いと思います。ただし、必ずしもこの法則に当てはまるわけでないと思います。
| return row * width + col | ||
|
|
||
| def union_connected_lands(row, col): | ||
| dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)] |
| dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)] | ||
| for dr, dc in dirs: | ||
| next_row, next_col = row + dr, col + dc | ||
| if not (0 <= next_row < height and 0 <= next_col < width): |
There was a problem hiding this comment.
右方向とした方向のみ考慮すれば、 0<= next_row と 0 <= next_col の条件は消せると思います。
さらに、
for h in range(height - 1):
for w in range(width - 1):
とすれば、この if 文を消せると思います。
| LAND = 1 | ||
| WATER = 0 | ||
| height, width = len(grid), len(grid[0]) | ||
| seen = [ [False] * width for _ in range(height)] |
| max_area = 0 | ||
| for h in range(height): | ||
| for w in range(width): | ||
| if grid[h][w] == LAND: |
There was a problem hiding this comment.
calc_area_while_removing() の中で if grid[row][col] == WATER: をしているため、この条件は不要だと思います。
| ```python | ||
| class UnionFind: | ||
| def __init__(self, size): | ||
| self.groups = [i for i in range(size)] |
There was a problem hiding this comment.
好みの範囲な気もしますが、[i for i in range(size)]はlist(range(size))でも良いように思いました。後者の方が単にlistにしたいだけだというのがすぐわかる気がします。
There was a problem hiding this comment.
ありがとうございます。rangeでsequenceを生成してそのままlistに変換するのがシンプルでいいですね。
https://leetcode.com/problems/max-area-of-island/