728x90
#3190 뱀 https://www.acmicpc.net/problem/3190
3190번: 뱀
'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임
www.acmicpc.net
문제가 짧아서인지 알고리즘을 꽤 풀어내서인지는 잘 모르겠지만 문제를 푸는 방법이 명료하게 보였다.
그래서 바로바로 구현했다.
뱀의 이동을 고민하던 터에, 큐를 사용하면 된다는 아이디어가 떠올랐고 적중했다.
from copy import deepcopy
n = int(input())
maps = [[0 for _ in range(n)] for __ in range(n)]
for _ in range(int(input())):
r, c = map(int, input().split())
maps[r - 1][c - 1] = 9 # apple
move_cnt = int(input())
# [times, direction], direction -> L(왼쪽), D(오른쪽)
moves = []
for _ in range(move_cnt):
x, y = input().split()
moves.append([int(x), y])
# 시작할 때 뱀의 길이는 1이다. 뱀은 맨위 맨좌측에 위치한다.
snake = [[0, 0]] # 행, 열
maps[0][0] = 1
# 뱀은 처음에 오른쪽을 향한다.
direction = 3 # 방향값 설정 0(위), 1(왼쪽), 2(아래쪽), 3(오른쪽)
def move_to_direciton(direction):
head = deepcopy(snake[-1])
if direction == 0:
head[0] -= 1
elif direction == 1:
head[1] -= 1
elif direction == 2:
head[0] += 1
elif direction == 3:
head[1] += 1
else:
return print("direction setting error")
return head
def valid_move(head):
return (0 <= head[0] < n and 0 <= head[1] < n) and (maps[head[0]][head[1]] != 1)
def change_direction(d):
global direction
if d == "D":
direction = direction - 1 if direction - 1 >= 0 else 3
else: # d == "L"
direction = (direction + 1) % 4
# 정답 계산
times = 0
while True:
if len(moves) and times == moves[0][0]:
_, d = moves.pop(0)
change_direction(d)
# 뱀은 몸길이를 늘려 머리를 다음 칸에 위치시킨다.
next_head = move_to_direciton(direction)
# 벽이나 자기자신의 몸과 부딪히면 게임이 끝난다.
if not valid_move(next_head):
times += 1
break
# 이동한 칸에 사과가 있다면, 그 칸에 있던 사과가 없어지고 꼬리는 움직이지 않는다.
if maps[next_head[0]][next_head[1]] == 9:
snake.append(next_head)
maps[next_head[0]][next_head[1]] = 1
# 이동한 칸에 사과가 없다면, 몸길이를 줄여서 꼬리가 위치한 칸을 비워준다. 즉 몸길이는 변하지 않는다.
else:
snake.append(next_head)
maps[next_head[0]][next_head[1]] = 1
x, y = snake.pop(0)
maps[x][y] = 0
times += 1
# print(times, direction, snake)
# for m in maps:
# print(m)
print(times)
# times를 언제 올려주냐에 따른 차이가 생기는게 신기하네.. -> 블로그 포스팅
문제는 times를 구하는 부분이었다.
while을 시작할 때 times+=1을 했을 때에는 틀린 값이 나왔다.
여러 도전을 하던 차에 위와 같은 형태로 times를 올린 경우에 정답이 나왔다.
사실 이유는 잘 모르겠다... 그래도 맞췄으니 일단은...
'Algorithm > acmicpc.net' 카테고리의 다른 글
구현 진짜 힘들다.... (#17144 미세먼지 안녕!) (0) | 2024.04.03 |
---|---|
구현은 빡시다. (#15683 감시) (0) | 2024.03.27 |
좌표를 헷갈리지 말 것!! (#14499 주사위 굴리기) (2) | 2024.03.23 |
빡구현은 체력전이다. (#14503 로봇청소기) (0) | 2024.03.21 |
파이썬 시간초과는 논리도 필요해요. (#14888 연산자 끼워넣기) (0) | 2024.03.20 |