반응형
https://www.acmicpc.net/problem/16236
16236번: 아기 상어
N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가지고 있고, 이 크기는 자연수이다. 가장 처음에 아기 상어의 크기는 2이고, 아기 상어는 1초에 상하좌우로 인접한 한 칸씩 이동한다. 아기 상어는 자신의 크기보다 큰 물고기가 있는 칸은 지나갈 수 없고, 나머지 칸은 모두 지나갈 수 있다. 아기 상어는 자신의 크
www.acmicpc.net


bfs + heapq로 풀어낼 수 있는 문제.
현재 위치에서
1. bfs로 '잡아먹을 수 있는 물고기 좌표'를 탐색한다.
2. 탐색한 물고기 좌표를 heapq 자료구조에 저장한다. 자료구조의 정렬 우선순위는 '거리, y좌표, x좌표'다.
3. 잡아먹은 물고기 개수를 업데이트한다. 상어 크기와 같아질 경우 상어 크기를 1 키우고 잡아먹은 물고기 개수를 초기화한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from collections import deque | |
import heapq | |
n = int(sys.stdin.readline()) | |
maps = [] | |
for y in range(n): | |
arr = list(map(int, sys.stdin.readline().split())) | |
for x in range(len(arr)): | |
if arr[x] == 9: | |
start = (y, x, 0) | |
maps.append(arr) | |
def find_min_dist(start, maps, current_size): | |
dirs = [(0,1),(0,-1),(1,0),(-1,0)] | |
queue = deque() | |
queue.append(start) | |
y, x, cnt = start | |
# 시작 위치 값을 0으로 변경. | |
maps[y][x] = 0 | |
# min_dist는 heapq구조. (cnt, y, x) 형태로 저장한다. | |
min_dist = [] | |
visited = set() | |
while queue: | |
y, x, cnt = queue.popleft() | |
visited.add((y, x)) | |
for dy, dx in dirs: | |
ny, nx = y + dy, x + dx | |
if 0 <= ny < len(maps) and 0 <= nx < len(maps) and (ny, nx) not in visited: | |
visited.add((ny, nx)) | |
# 다음 칸으로 이동할 수 있는 경우 | |
if maps[ny][nx] == 0 or maps[ny][nx] == current_size: | |
queue.append((ny, nx, cnt + 1)) | |
continue | |
# 지나갈 수 없는 경우 | |
if maps[ny][nx] > current_size: | |
continue | |
else: | |
# 먹을 수 있는 경우 | |
heapq.heappush(min_dist, (cnt+1, ny, nx)) | |
# 먹을 수 있는 후보군 중 조건에 부합하는 것 | |
if min_dist: | |
return min_dist[0] | |
else: | |
return None | |
time = 0 | |
current_size = 2 | |
already_eat = 0 | |
while True: | |
next_value = find_min_dist(start, maps, current_size) | |
# 더 이상 먹을 수 있는 물고기가 없는 경우 | |
if next_value is None: | |
break | |
# cnt = 다음 물고기를 먹기까지 걸린 시간. | |
cnt, ny, nx = next_value | |
time += cnt | |
# 먹은 물고기 개수를 센다. | |
already_eat += 1 | |
# 현재 크기만큼 먹었으면 크기를 1 키우고 개수를 초기화한다. | |
if already_eat == current_size: | |
current_size += 1 | |
already_eat = 0 | |
# 다음 출발점을 정한다. | |
start = (ny, nx, 0) | |
print(time) | |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 2019 카카오 recruit - 무지의 먹방 라이브 (Level 3) (0) | 2020.03.25 |
---|---|
[Python] 프로그래머스. 2018 카카오 recruit - 캐시 (Level 2) (0) | 2020.03.24 |
[Python] 구름. 공연 좌석 (0) | 2020.03.19 |
[Python] 구름. 달걀 부화기 (0) | 2020.03.18 |
[Python] 구름. 외주 (0) | 2020.03.17 |