코딩테스트/Python

[이코테 강좌] Brute force 1번 상하 좌우 - python

brotoo 2022. 1. 4. 19:13

답안 코드


n = int(input())
# 초기값 설정
x, y = 1, 1
plans = input().split()

# 아래 MOVE TYPE에 따른 이동 방향 체크
# x좌표와 y 좌표 문자를 각각 같은 인덱스로 설정해주는 방식이다.
# 체크해서 활용하자.
dx = [0, 0, -1 ,1]
dy = [-1, 1, 0, 0]
move_types = ['L', 'R', 'U', 'D']

#이중 포문 사용해서 이렇게 돌려서 타입을 체크하는 방식이다.
for plan in plans:
    for i in range(len(move_types)):
        if plan == move_types[i]:
            nx = x + dx[i]
            ny = y + dy[i]

        if nx < 1 or ny < 1 or nx > n or ny > n:
            continue
        x, y = nx, ny

print(x, y)

 

내 코드


n = int(input())
move_list = list(map(str, input().split(" ")))

init = [1, 1]
direction = {"R" : [0, 1], "L" : [0, -1], "U" : [-1, 0], "D" : [1, 0]}

for line in move_list:  
    init[0] += direction[line][0]
    init[1] += direction[line][1]
    if init[0] < 1 or init[0] > n or init[1] < 1 or init[1] > n:
        init[0] -= direction[line][0] 
        init[1] -= direction[line][1]

print(init[0], init[1], end = ' ')

 

리뷰


결국 각각을 딕셔너리화 시켜서 해준 것은 모범 답안과 동일한 느낌이지만 

dx = [0, 0, -1 ,1]
dy = [-1, 1, 0, 0]
move_types = ['L', 'R', 'U', 'D']

이 방식 처럼 각각 어짜피 리스트에서 정렬될 일 없으니 각각 x , y 좌표를 하나씩 리스트를 만들어서 돌려서 확인하면 될 문제였다.

 

어찌보면 방향키이다. 그리고 그에 맞는 범위 규정만 지켜주면 쉽게 풀리는 문제이다.