๋๋น์ฐ์ ํ์(BFS)๋ก ์์ด์ ํ์ฌ ์์น์์ ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ๋ฅผ ํ์ํ๋ค.
๊ฑฐ๋ฆฌ๊ฐ ๊ฐ๊น์ด ๋ฌผ๊ณ ๊ธฐ > ๊ฐ์ฅ ์์ ์๋ ๋ฌผ๊ณ ๊ธฐ > ๊ฐ์ฅ ์ผ์ชฝ์ ์๋ ๋ฌผ๊ณ ๊ธฐBFS ํจ์๋ฅผ while๋ฌธ์ผ๋ก ๊ณ์ ๋๋ฆฌ๋ฉด์, ํจ์๊ฐ ํ๋ฒ ๋๋ ๋๋ง๋ค ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ ๋ฆฌ์คํธ์์ ๊ฐ์ฅ ์ฐ์ ์์๊ฐ ๋์ ๋ฌผ๊ณ ๊ธฐ ํ ๋ง๋ฆฌ๋ฅผ ๋จน๋๋ค.
์ด ๋ฌธ์ ์ ํด๊ฒฐ ํคํฌ์ธํธ๋ ****
ํ์ ๊ณผ์ ๊ณผ ๋ฌผ๊ณ ๊ธฐ๋ฅผ ๋จน๊ณ ์ ๋ฐ์ดํธ ์ํค๋ ๊ณผ์ ์ ๋ถ๋ฆฌํ ๊ฒ์ด๋ค!
import sys
from collections import deque
# readlline ๋ค์ ๊ดํธ๋ฅผ ๋ฃ์ผ๋ฉด ์๋ฌ๊ฐ ์๊น ์กฐ์ฌ!
input = sys.stdin.readline
n = int(input())
space = []
# ์์ด์ ์์น์ ํฌ๊ธฐ
shark_x, shark_y, shark_size = 0, 0, 2
for i in range(n):
space.append(list(map(int, input().split())))
for j in range(n):
if space[i][j] == 9:
shark_x = i
shark_y = j
# ์ํ์ข์ฐ
dx, dy = [0, 0, 1, -1], [1, -1, 0, 0]
def eat_fish(x, y, shark_size):
visited = [[0] * n for _ in range(n)]
# ์ด๋ํ ๊ฑฐ๋ฆฌ
distance = [[0] * n for _ in range(n)]
queue = deque()
queue.append((x, y))
visited[x][y] = 1
# ์์ฌ ๋ฆฌ์คํธ
fishes = []
while queue:
cur_x, cur_y = queue.popleft()
for i in range(4):
nx, ny = cur_x + dx[i], cur_y + dy[i]
if 0 <= nx < n and 0 <= ny < n and visited[nx][ny] == 0:
# ์ด๋ํ ์ ์๋ค๋ฉด
if space[nx][ny] <= shark_size:
queue.append((nx, ny))
visited[nx][ny] = 1
distance[nx][ny] = distance[cur_x][cur_y] + 1
if space[nx][ny] < shark_size and space[nx][ny] != 0:
fishes.append((nx, ny, distance[nx][ny]))
# ์ฐ์ ์์ : ๊ฑฐ๋ฆฌ๊ฐ ๊ฐ๊น์ด ๋ฌผ๊ณ ๊ธฐ > ๊ฐ์ฅ ์์ ์๋ ๋ฌผ๊ณ ๊ธฐ > ๊ฐ์ฅ ์ผ์ชฝ์ ์๋ ๋ฌผ๊ณ ๊ธฐ
# ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํด์ผ pop ํ์ ๋ ๊ฐ์ฅ ๋ค์ ์๋ ๊ฐ์ด ๊ฐ์ฅ ์ ํฉํ fish!
return sorted(fishes, key=lambda x: (-x[2], -x[0], -x[1]))
time = 0
count = 0
while True:
eatable_fishes = eat_fish(shark_x, shark_y, shark_size)
# ๋ ์ด์ ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ๊ฐ ๊ณต๊ฐ์ ์๋ค๋ฉด ์๋ง์์ด์๊ฒ ๋์ ์์ฒญ
if len(eatable_fishes) == 0:
break
# ๋จน์ ๋ฌผ๊ณ ๊ธฐ pick <- ์ด๋ฏธ ์ ๋ ฌ๋ ์ํ
nx, ny, dist = eatable_fishes.pop()
# ์์ง์ด๋ ์นธ ์ = ์๊ฐ
time += dist
# ์์ด๊ฐ ์์๋ ์์น์ ๋จน์ ๋ฌผ๊ณ ๊ธฐ๊ฐ ์์๋ ์์น๋ฅผ 0์ผ๋ก ๋ง๋ค๊ธฐ
space[shark_x][shark_y], space[nx][ny] = 0, 0
# ์์ด ์ขํ๋ฅผ ๋จน์ ๋ฌผ๊ณ ๊ธฐ ์ขํ๋ก ์ด๋
shark_x, shark_y = nx, ny
# ๋จน์ ๋ฌผ๊ณ ๊ธฐ ๊ฐ์๋ ์์ด ์ฌ์ด์ฆ ์
๋ฐ์ดํธ
count += 1
if count == shark_size:
shark_size += 1
count = 0
print(time)