|
| 1 | +import itertools |
| 2 | +import sys |
| 3 | + |
| 4 | +read = lambda: sys.stdin.readline().rstrip() |
| 5 | + |
| 6 | + |
| 7 | +class Problem: |
| 8 | + def __init__(self): |
| 9 | + self.n, self.m = map(int, read().split()) |
| 10 | + self.matrix = [list(map(int, read().split())) for _ in range(self.n)] |
| 11 | + |
| 12 | + def solve(self) -> None: |
| 13 | + maximum = 0 |
| 14 | + for x, y in itertools.product(range(self.m), range(self.n)): |
| 15 | + maximum = max( |
| 16 | + maximum, |
| 17 | + self.find_normal_maximum(x, y), |
| 18 | + ) |
| 19 | + |
| 20 | + maximum = max( |
| 21 | + maximum, |
| 22 | + self.find_special_maximum(x, y), |
| 23 | + ) |
| 24 | + |
| 25 | + print(maximum) |
| 26 | + |
| 27 | + def find_normal_maximum(self, start_x: int, start_y: int) -> int: |
| 28 | + stack, maximum = [((start_x, start_y), 1, self.matrix[start_y][start_x], {(start_x, start_y)})], 0 |
| 29 | + |
| 30 | + while stack: |
| 31 | + (x, y), current_depth, current_sum, visited = stack.pop() |
| 32 | + if current_depth == 4: |
| 33 | + if current_sum > maximum: |
| 34 | + maximum = current_sum |
| 35 | + continue |
| 36 | + |
| 37 | + for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: |
| 38 | + nx, ny = x + dx, y + dy |
| 39 | + |
| 40 | + if 0 <= nx < self.m and 0 <= ny < self.n and (nx, ny) not in visited: |
| 41 | + stack.append( |
| 42 | + ( |
| 43 | + (nx, ny), |
| 44 | + current_depth + 1, |
| 45 | + current_sum + self.matrix[ny][nx], |
| 46 | + visited | {(nx, ny)}, |
| 47 | + ) |
| 48 | + ) |
| 49 | + |
| 50 | + return maximum |
| 51 | + |
| 52 | + def find_special_maximum(self, start_x: int, start_y: int) -> int: |
| 53 | + candidates = [] |
| 54 | + for shape in [ |
| 55 | + [(0, 0), (0, 1), (0, 2), (-1, 1)], |
| 56 | + [(0, 0), (0, 1), (0, 2), (1, 1)], |
| 57 | + [(0, 0), (1, 0), (2, 0), (1, 1)], |
| 58 | + [(0, 0), (1, 0), (2, 0), (1, -1)], |
| 59 | + ]: |
| 60 | + total, is_valid = 0, True |
| 61 | + for dy, dx in shape: |
| 62 | + nx, ny = start_x + dx, start_y + dy |
| 63 | + if not (0 <= ny < self.n and 0 <= nx < self.m): |
| 64 | + is_valid = False |
| 65 | + break |
| 66 | + |
| 67 | + total += self.matrix[ny][nx] |
| 68 | + |
| 69 | + if is_valid: |
| 70 | + candidates.append(total) |
| 71 | + |
| 72 | + return max(candidates or [0]) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + Problem().solve() |
0 commit comments