좌표를 이동하면서 중복되지 않은 길을 걸었는지를 체크해야 한다.
예를 들어 (0,0) -> (0,1) 로 이동했을 때
걸은 길은 ((0,0),(0,1)) 로 표현 할 수 있다. (from,to)
이때, (0,0) -> (0,1) 로 이동한 길은 (0,1) -> (0,0)으로 이동한 길과 같다.
따라서 routes 에 저장을 할 때 (from,to)와 (to,from) 을 같이 저장하고
routes에 저장된 길의 개수를 2로 나누면 중복되지 않은 걸은 길의 갯수를 구할 수 있다.
문제에서는 거리를 구하라고 했으나 한번에 1칸씩밖에 이동하지 못하므로 길의 갯수는 길의 거리와 같다.
def solution(dirs):
def can_visit(pos):
(x, y) = pos
return -5 <= x <= 5 and -5 <= y <= 5
def next(pos, command):
(x, y) = pos
if command == 'U':
return (x-1, y)
if command == 'D':
return (x+1, y)
if command == 'L':
return (x, y-1)
if command == 'R':
return (x, y+1)
return pos
current_pos = (0, 0)
routes = set()
for dir in dirs:
next_pos = next(current_pos, dir)
if can_visit(next_pos):
routes.add((current_pos, next_pos))
routes.add((next_pos, current_pos))
current_pos = next_pos
return len(routes)//2