|
| 1 | +import heapq |
| 2 | +import sys |
| 3 | + |
| 4 | +read = lambda: sys.stdin.readline().rstrip() |
| 5 | + |
| 6 | + |
| 7 | +class Problem: |
| 8 | + def __init__(self): |
| 9 | + self.n = int(read()) |
| 10 | + self.graph = [list(map(int, read().split())) for _ in range(self.n)] |
| 11 | + |
| 12 | + def solve(self) -> None: |
| 13 | + graph = self.graph |
| 14 | + shark = self.find_shark(graph) |
| 15 | + |
| 16 | + shark_size, weight, time = 2, 0, 0 |
| 17 | + while True: |
| 18 | + found = self.find_nearest_fish( |
| 19 | + graph, |
| 20 | + shark, |
| 21 | + shark_size, |
| 22 | + ) |
| 23 | + if not found: |
| 24 | + break |
| 25 | + |
| 26 | + (y, x), append_time = found |
| 27 | + |
| 28 | + weight += 1 |
| 29 | + if weight == shark_size: |
| 30 | + shark_size += 1 |
| 31 | + weight = 0 |
| 32 | + |
| 33 | + time += append_time |
| 34 | + graph[shark[0]][shark[1]] = 0 |
| 35 | + shark = (y, x) |
| 36 | + graph[shark[0]][shark[1]] = 9 |
| 37 | + |
| 38 | + print(time) |
| 39 | + |
| 40 | + def find_shark( |
| 41 | + self, |
| 42 | + graph: list[list[int]], |
| 43 | + ) -> tuple[int, int]: |
| 44 | + for row in range(self.n): |
| 45 | + for col in range(self.n): |
| 46 | + if graph[row][col] == 9: |
| 47 | + return row, col |
| 48 | + |
| 49 | + def find_nearest_fish( |
| 50 | + self, |
| 51 | + graph: list[list[int]], |
| 52 | + shark: tuple[int, int], |
| 53 | + shark_size: int, |
| 54 | + ) -> tuple[tuple[int, int], int] | None: |
| 55 | + queue, visited, found = [(shark, 0)], {shark}, [] |
| 56 | + while queue and not found: |
| 57 | + candidates = [] |
| 58 | + for (y, x), time in queue: |
| 59 | + for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: |
| 60 | + if ( |
| 61 | + (0 <= x + dx < self.n and 0 <= y + dy < self.n) |
| 62 | + and graph[y + dy][x + dx] <= shark_size |
| 63 | + and ( |
| 64 | + y + dy, |
| 65 | + x + dx, |
| 66 | + ) |
| 67 | + not in visited |
| 68 | + ): |
| 69 | + candidates.append(((y + dy, x + dx), time + 1)) |
| 70 | + visited.add((y + dy, x + dx)) |
| 71 | + if 0 < graph[y + dy][x + dx] < shark_size: |
| 72 | + heapq.heappush( |
| 73 | + found, ((y + dy, x + dx), ((y + dy, x + dx), time + 1)) |
| 74 | + ) |
| 75 | + |
| 76 | + queue = candidates |
| 77 | + |
| 78 | + if found: |
| 79 | + return heapq.heappop(found)[1] |
| 80 | + |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + Problem().solve() |
0 commit comments