[이코테] 구현_뱀 (python) (다시 풀어보기)

juyeon·2022년 7월 19일
0

문제

나의 풀이

1. 성공..but 너무 for문만 쓰나?ㅠㅠ

from collections import deque

n, k = int(input()), int(input()) # 보드의 크기, 사과의 개수
# 사과의 위치 행, 열(index로 변환)
apple = [list(map(lambda x: x - 1, (map(int, input().split())))) for _ in range(k)]

l = int(input()) # 뱀의 방향 변환 횟수
# 뱀의 방향 전환 정보, 시간 list
snake_turn = [0] * 10001
for _ in range(l): # x초 뒤에 c: 왼쪽(L)/오른쪽(D)으로 90도 회전
	x, c = list(input().split())
	snake_turn[int(x)] = c
    
snake = deque([[0, 0]]) # 뱀의 정보

go, turn = [(0, 1), (1, 0), (0, -1), (-1, 0)], 0 # 이동(동남서북), 현재 방향 index

for t in range(1, 10001):
	# 뱀이 이동
	head = list(map(lambda a, b: a + b, snake[-1], go[turn]))
    
	# 뱀이 벽 또는 자기 자신과 부딪히면, 시간을 출력하고 게임이 끝남
	if head[0] < 0 or head[0] >= n or head[1] < 0 or head[1] >= n or head in snake:
		print(t)
		break
        
	snake.append(head) # 뱀의 머리칸 추가
	
	# 머리칸에 사과가 있다면 먹고, 없다면 꼬리칸 비우기
	apple.remove(head) if head in apple else snake.popleft()
	
	# 방향 전환
	if snake_turn[t] != 0:
		turn = (turn + 1) % 4 if snake_turn[t] == 'D' else (turn - 1) % 4

: index 0을 제거하기 위해서 popleft, 즉 deque가 필요했음

  • 백준: 메모리:32468KB 시간:120ms 코드 길이:1217B

2. 실패?

from collections import deque

n, k = int(input()), int(input()) # 보드의 크기, 사과의 개수

apple = []
for _ in range(k):
    a, b = map(int, input().split())
    apple.append((a-1, b-1)) # 사과의 위치: 행, 열 (좌표는 1행 1열부터 시작하도록)
    
L = int(input()) # 뱀의 방향 변환 횟수

# 뱀의 방향 전환 정보
turn_list = [0] * (10001) # x <= 10000
for _ in range(L): # x초 뒤에 c로 회전: 왼쪽(L), 오른쪽(D)
	x, c = list(input().split())
	turn_list[int(x)]
    
snake = deque([[0, 0]]) # 뱀의 현재 위치
snake_head = 0 # 동쪽
go_list = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 동남서북

for time in range(1, 10001):
    # 뱀의 머리 위치 갱신
    head_x, head_y = map(lambda a, b: a + b, snake[-1], go_list[snake_head])

    # 벽 또는 자기 자신의 몸과 부딪히면, break
    if head_x < 0 or head_y < 0 or head_x >= n or head_y >= n or (head_x, head_y) in snake:
        print(time)
        break
    
    snake.append((head_x, head_y)) # else: 뱀의 머리 추가
	
    if (head_x, head_y) in apple:
        apple.remove((head_x, head_y)) # 꼬리는 그대로, 사과를 먹음
    else: 
	    snake.popleft() # 몸길이는 그대로, 꼬리를 비워줌
     
	# 방향 회전 
    if turn_list[time] == 'L': # 0, 1, 2, 3 -> 3, 0, 1, 2. 왼쪽으로
        snake_head = (snake_head - 1) % 4
    elif turn_list[time] == 'D': # 0, 1, 2, 3, -> 2, 3, 4, 0. 오른쪽으로
        snake_head = (snake_head + 1) % 4
profile
내 인생의 주연

0개의 댓글