2025-10-22 00:27:40 +09:00

61 lines
1.6 KiB
Python

from collections import deque
N = int(input())
area = []
shark = (0,0)
for i in range(N) :
area.append(list(map(int, input().split())))
for j in range(N) :
if area[i][j] == 9 :
shark = (i,j)
area[i][j] = 0
# 현재 상어의 위치에서 먹을 수 있는 물고기들 중
# 우선순위가 가장 높은 물고기의 위치와 거리를 반환하는 함수
# 입력변수는 현재 상어의 위치좌표((y,x) 형태의 튜플)와 상어의 크기
def fish(current, size) :
y, x = current
visited = [[False]*N for _ in range(N)]
q = deque()
q.append((x,y,0))
visited[y][x] = True
result = []
while q :
cur_x, cur_y, cur_dist = q.popleft()
for dx, dy in [(-1,0), (1,0), (0,1), (0,-1)] :
next_x, next_y = cur_x + dx, cur_y + dy
if 0<=next_x<N and 0<=next_y<N and not visited[next_y][next_x] and area[next_y][next_x] <= size :
q.append((next_x, next_y, cur_dist + 1))
visited[next_y][next_x] = True
if 0<area[next_y][next_x]<size :
result.append((next_x, next_y, cur_dist + 1))
if result :
result.sort(key=lambda x: (x[2], x[1], x[0]))
return result[0]
else :
return None
shark_size = 2
eatCount = 0
total_time = 0
while (res := fish(shark, shark_size)) is not None :
cur_x, cur_y, dist = res
shark = (cur_y, cur_x)
area[cur_y][cur_x] = 0
total_time += dist
eatCount += 1
if eatCount == shark_size :
eatCount = 0
shark_size += 1
print(total_time)