|
| 1 | +from collections import deque |
| 2 | +from typing import List, Tuple |
| 3 | + |
| 4 | + |
| 5 | +def solution(land: List[List[int]]) -> int: |
| 6 | + n, m = len(land), len(land[0]) |
| 7 | + graph = find_graph(n, m, land) |
| 8 | + |
| 9 | + maximum = 0 |
| 10 | + for col in range(m): |
| 11 | + amount, visited = 0, set() |
| 12 | + |
| 13 | + for row in range(n): |
| 14 | + group_id, value = graph[row][col] |
| 15 | + if group_id != 0 and group_id not in visited: |
| 16 | + visited.add(group_id) |
| 17 | + amount += value |
| 18 | + |
| 19 | + maximum = max(maximum, amount) |
| 20 | + |
| 21 | + return maximum |
| 22 | + |
| 23 | + |
| 24 | +def find_graph(n: int, m: int, land: List[List[int]]) -> List[List[Tuple[int, int]]]: |
| 25 | + graph, visited, count = [[(0, 0) for _ in range(m)] for _ in range(n)], set(), 0 |
| 26 | + |
| 27 | + for y in range(n): |
| 28 | + for x in range(m): |
| 29 | + if land[y][x] == 1 and (x, y) not in visited: |
| 30 | + stack, cached, count = deque([(x, y)]), set(), count + 1 |
| 31 | + |
| 32 | + while stack: |
| 33 | + c, r = stack.pop() |
| 34 | + visited.add((c, r)) |
| 35 | + cached.add((c, r)) |
| 36 | + |
| 37 | + for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: |
| 38 | + nx, ny = c + dx, r + dy |
| 39 | + if (0 <= nx < m) and (0 <= ny < n) and land[ny][nx] == 1 and (nx, ny) not in visited: |
| 40 | + stack.append((nx, ny)) |
| 41 | + |
| 42 | + group_id, amount = count, len(cached) |
| 43 | + for c, r in cached: |
| 44 | + graph[r][c] = (group_id, amount) |
| 45 | + |
| 46 | + return graph |
0 commit comments