Skip to content

Commit 06661a3

Browse files
authored
Create 1.py
1 parent 77dbf7a commit 06661a3

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

19/1.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
from collections import deque
2+
INF = 1e9 # 무한 상수
3+
4+
# 맵의 크기 N 입력
5+
n = int(input())
6+
7+
# 전체 모든 칸에 대한 정보 입력
8+
array = []
9+
for i in range(n):
10+
array.append(list(map(int, input().split())))
11+
12+
# 아기 상어의 현재 크기와 현재 위치를 나타내는 변수
13+
now_size = 2
14+
now_x, now_y = 0, 0
15+
16+
# 아기 상어의 시작 위치를 찾은 뒤에 그 위치엔 아무것도 없다고 처리
17+
for i in range(n):
18+
for j in range(n):
19+
if array[i][j] == 9:
20+
now_x, now_y = i, j
21+
array[now_x][now_y] = 0
22+
23+
dx = [-1, 0, 1, 0]
24+
dy = [0, 1, 0, -1]
25+
26+
# 모든 위치까지의 '최단 거리만' 계산하는 BFS 함수
27+
def bfs():
28+
# 값이 -1이라면 도달할 수 없다는 의미 (초기화)
29+
dist = [[-1] * n for _ in range(n)]
30+
# 시작 위치는 도달이 가능하며 거리는 0
31+
q = deque([(now_x, now_y)])
32+
dist[now_x][now_y] = 0
33+
while q:
34+
x, y = q.popleft()
35+
for i in range(4):
36+
nx = x + dx[i]
37+
ny = y + dy[i]
38+
if 0 <= nx and nx < n and 0 <= ny and ny < n:
39+
# 자신의 크기보다 작거나 같은 경우에 지나갈 수 있음
40+
if dist[nx][ny] == -1 and array[nx][ny] <= now_size:
41+
dist[nx][ny] = dist[x][y] + 1
42+
q.append((nx, ny))
43+
# 모든 위치까지의 최단 거리 테이블 반환
44+
return dist
45+
46+
# 최단 거리 테이블이 주어졌을 때, 먹을 상어를 찾는 함수
47+
def find(dist):
48+
x, y = 0, 0
49+
min_dist = INF
50+
for i in range(n):
51+
for j in range(n):
52+
# 도달이 가능하면서 먹을 수 있는 물고기일 때
53+
if dist[i][j] != -1 and 1 <= array[i][j] and array[i][j] < now_size:
54+
# 가장 가까운 물고기 한 마리만 선택
55+
if dist[i][j] < min_dist:
56+
x, y = i, j
57+
min_dist = dist[i][j]
58+
if min_dist == INF: # 먹을 수 있는 상어가 없는 경우
59+
return None
60+
else:
61+
return x, y, min_dist # 먹을 상어의 위치와 최단 거리
62+
63+
result = 0 # 최종 답안
64+
ate = 0 # 현재 크기에서 먹은 양
65+
66+
while True:
67+
# 먹을 수 있는 상어의 위치 찾기
68+
value = find(bfs())
69+
# 먹을 수 있는 상어가 없는 경우, 현재까지 움직인 거리 출력
70+
if value == None:
71+
print(result)
72+
break
73+
else:
74+
# 현재 위치 갱신 및 이동 거리 변경
75+
now_x, now_y = value[0], value[1]
76+
result += value[2]
77+
# 먹은 위치에는 이제 아무것도 없도록 처리
78+
array[now_x][now_y] = 0
79+
ate += 1
80+
# 자신의 현재 크기 이상으로 먹은 경우, 크기 증가
81+
if ate >= now_size:
82+
now_size += 1
83+
ate = 0

0 commit comments

Comments
 (0)