1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution: def maxAreaOfIsland(self, g: List[List[int]]) -> int: size_y = len(g) size_x = len(g[0]) visited_map = {} def get_neighers(y, x): offset = [-1, 1] result = [] for o in offset: new_y = y + o if 0 <= new_y < size_y: if g[new_y][x] == 1 and (new_y, x) not in visited_map.keys(): result.append((new_y, x)) new_x = x + o if 0 <= new_x < size_x: if g[y][new_x] == 1 and (y, new_x) not in visited_map.keys(): result.append((y, new_x)) return result def dfs(y, x): if g[y][x] == 0: return 0 if (y, x) in visited_map.keys(): return 0 visited_map[(y, x)] = 1 neighers = get_neighers(y, x) result = 0 for n_y, n_x in neighers: result += dfs(n_y, n_x) return result + 1 result = 0 for y in range(size_y): for x in range(size_x): if g[y][x] == 0: continue if (y, x) in visited_map.keys(): continue result = max(result, dfs(y, x)) return result
|