Skip to content

Commit f0c1549

Browse files
committed
[BOJ] #16236. 아기 상어 / 골드3 / 70분 / 실패
1 parent 10eeae5 commit f0c1549

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
def bfs(sx, sy, shark_size):
6+
# 방문 배열과 거리 기록
7+
visited = [[-1]*n for _ in range(n)]
8+
visited[sx][sy] = 0
9+
queue = deque([(sx, sy)])
10+
fishes = [] # 먹을 수 있는 물고기 후보들
11+
12+
while queue:
13+
x, y = queue.popleft()
14+
for dx, dy in directions:
15+
nx, ny = x + dx, y + dy
16+
# 새로운 좌표가 공간 내에 있고 아직 방문하지 않은 경우
17+
if 0 <= nx < n and 0 <= ny < n and visited[nx][ny] == -1:
18+
# 이동 가능한 칸: 빈 칸이거나, 물고기가 있어도 크기가 shark_size 이하인 경우
19+
if space[nx][ny] <= shark_size:
20+
visited[nx][ny] = visited[x][y] + 1
21+
# 먹을 수 있는 물고기: 값이 0이 아니고 아기 상어 크기보다 작은 경우
22+
if 0 < space[nx][ny] < shark_size:
23+
fishes.append((visited[nx][ny], nx, ny))
24+
queue.append((nx, ny))
25+
if not fishes:
26+
return None # 먹을 수 있는 물고기가 없음
27+
28+
# 문제 조건대로 정렬: 거리, 행, 열, 순
29+
fishes.sort(key=lambda x: (x[0], x[1], x[2]))
30+
return fishes[0] # 가장 적합한 물고기
31+
32+
33+
n = int(input()) # 공간의 크기
34+
space = [] # 공간의 상태
35+
for _ in range(n):
36+
space.append(list(map(int, input().split())))
37+
38+
39+
# 아기상어 위치 구하기
40+
sx, sy = 0, 0
41+
for i in range(n):
42+
for j in range(n):
43+
if space[i][j] == 9:
44+
sx, sy = i, j
45+
space[sx][sy] = 0 # 아기 상어의 시작 위치는 빈 칸(0)으로 처리
46+
47+
# 초기 설정
48+
shark_size = 2 # 아기 상어 초기 크기
49+
eaten = 0 # 먹은 물고기 수
50+
time = 0 # 전체 소요시간
51+
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
52+
53+
# 시뮬레이션 수행
54+
while True:
55+
result = bfs(sx, sy, shark_size)
56+
if result is None: # 먹을 수 있는 물고기가 없으면 종료
57+
break
58+
59+
dist, fx, fy = result # 먹을 수 있는 물고기의 거리와 위치
60+
time += dist # 이동 시간 추가
61+
sx, sy = fx, fy # 아기 상어 위치 이동
62+
space[sx][sy] = 0 # 물고기를 먹었으므로 해당 칸을 빈 칸으로 만들기
63+
eaten += 1# 먹은 물고기 수
64+
65+
# 먹은 물고기 수가 현재 아기 상어 크기와 같으면 크기를 1 증가
66+
if eaten == shark_size:
67+
shark_size += 1
68+
eaten = 0
69+
70+
print(time)

0 commit comments

Comments
 (0)