방문 길이
코딩테스트 연습 > Summer/Winter Coding(~2018) > 방문 길이
https://programmers.co.kr/learn/courses/30/lessons/49994
# 문제 정리
- 입력: L,R,U,D로 구성된 문자열
- 과정:
1. 방향에 따른 좌표 변환에 대해 딕셔너리 형태로 저장한다.
2. 초기 위치값을 설정하고, 입력된 문자열(dir)에 맞추어 다음 위치값을 설정한다.
1) 이 때, 다음 위치값의 절대값이 5이하일 경우만 고려한다.
2) ☆ 해당 문제는 좌표변환의 정도를 보는 것이 아니라, 벡터에 대한 문제이므로
(1) 빈 리스트에 (현재위치,목표위치) (목표위치,현재위치)를 append한다.
(2) 현재 위치값을 다음위치값으로 갱신한다.
3. 리스트를 set을 통해 중복값을 제거한 뒤 //2 를 취한다.
# Input value
dirs = "ULURRDLLU"
now_x,now_y = 0,0 # Set start point
move = {'L':(0,-1),'R':(0,1),'U':(1,0),'D':(-1,0)} # Define move
destination = []
for d in dirs:
next_x,next_y = now_x+move[d][0],now_y+move[d][1] # Define next location
if abs(next_x) <= 5 and abs(next_y) <= 5: # Restrict range
destination.append((now_x,now_y,next_x,next_y)) # Consider now point and next point(because of path)
destination.append((next_x,next_y,now_x,now_y)) # Consider next point and now point(because of path)
now_x,now_y = next_x,next_y # Update start point
len(set(destination))/2
def solution(dirs):
now_x,now_y = 0,0
move = {'L':(0,-1),'R':(0,1),'U':(1,0),'D':(-1,0)}
destination = []
for d in dirs:
next_x,next_y = now_x+move[d][0],now_y+move[d][1]
if abs(next_x) <= 5 and abs(next_y) <= 5:
destination.append((now_x,now_y,next_x,next_y))
destination.append((next_x,next_y,now_x,now_y))
now_x,now_y = next_x,next_y
return len(set(destination))/2