문제
[어른 상어 백준 19237]
https://www.acmicpc.net/problem/19237
어른이 된 상어들이 냄새를 풍기며 이동하는 것을 구현하는 문제이다.
풀이
매초마다 모든 상어의 기능을 구현하는 문제이다. 상어마다 방향의 우선순위가 정해져있어 상어들이 다른 방향으로 이동하기 때문에 중점적으로 구현해야할 요소들이 있다.
- 상어들의 움직임을 고려해 새로운 공간을 반환하는 함수
- 냄새가 어떻게 바뀌는지 바꿔주는 함수
- 방향의 우선 순위 입력 받기
! 어려웠던 점
- 처음에 인덱스를 모두 통일하자는 생각에 우선 순위 리스트를 입력받는 코드를 짜는 데에 너무 헤맸다. 함수에서 -1을 넣어주는 한이 있더라도 입력부 코드에 너무 힘을 쏟진 말아야겠다
- 청소년 상어 문제에서 물고기의 움직임을 나타내는 함수를 만들 때 물고기 번호 순서대로 해야한다는 생각에 상어도 번호 순으로 하려다가 코드가 꼬였다. 리스트를 그냥 검사하는 것도 괜찮을 거 같다.
- 냄새가 없는 곳을 먼저 진입하는 것인데 자신의 냄새라도 있으면 이동한다라고 생각하고 코드를 짰다. 문제를 잘 확인하는 습관이 필요해 보인다.
전체적으로 많은 시간이 든 문제였다. 아직까지는 이정도 시뮬레이션 구현 문제는 버거운 거 같다.
함수의 인수, 변수의 이름 설정, 입력부 간단하게 하기 에 대한 개선이 필요해 보인다.
코드
n, m, k = map(int, input().split())
data = []
smell = [[[0, 0] for _ in range(n)] for _ in range(n)]
for i in range(n):
data.append(list(map(int, input().split())))
directions = list(map(int, input().split()))
priorities = []
for i in range(m):
temp = []
for j in range(4):
temp.append(list(map(int, input().split()))) # 너무 복잡하게 입력받지 말자
priorities.append(temp)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def update_smell():
for i in range(n):
for j in range(n):
if smell[i][j][1] > 0:
smell[i][j][1] -= 1
if data[i][j] != 0:
smell[i][j] = [data[i][j], k]
def move():
new_data = [[0] * n for _ in range(n)]
for x in range(n):
for y in range(n):
if data[x][y] != 0:
direction = directions[data[x][y] - 1]
breaker = False
for idx in priorities[data[x][y] - 1][direction - 1]:
nx = x + dx[idx - 1]
ny = y + dy[idx - 1]
if 0 <= nx < n and 0 <= ny < n:
if smell[nx][ny][1] == 0:
directions[data[x][y] - 1] = idx
if new_data[nx][ny] == 0:
new_data[nx][ny] = data[x][y]
else:
new_data[nx][ny] = min(new_data[nx][ny], data[x][y])
breaker = True
break
if breaker:
continue
for idx in priorities[data[x][y] - 1][direction - 1]:
nx = x + dx[idx - 1]
ny = y + dy[idx - 1]
if 0 <= nx < n and 0 <= ny < n:
if smell[nx][ny][0] == data[x][y]:
directions[data[x][y] - 1] = idx
new_data[nx][ny] = data[x][y]
break
return new_data
time = 0
while True:
update_smell()
new_data = move()
data = new_data
time += 1
check = True
for i in range(n):
for j in range(n):
if data[i][j] > 1:
check = False
if check:
print(time)
break
if time >= 1000:
print(-1)
break
해당 포스트는 이코테 - 동빈나 에 실린 답을 참고하여 작성했습니다.