[Python] 방문길이 [프로그래머스 Level 3]
문제 바로가기
풀이 1
def solution(dirs):
x, y = 0, 0
map = dict()
for command in dirs:
if command == 'U' and y < 5:
map[(x, y, x, y+1)] = True
y += 1
elif command == 'D' and y > -5:
map[(x, y-1, x, y)] = True
y -= 1
elif command == 'R' and x < 5:
map[(x, y, x+1, y)] = True
x += 1
elif command == 'L' and x > -5:
map[(x-1, y, x, y)] = True
x -= 1
return len(map)
풀이 2
def solution(dirs):
position = (0, 0)
command_dict = {
'U': (-1, 0),
'D': (1, 0),
'R': (0, 1),
'L': (0, -1)
}
check = set()
for command in dirs:
direction = command_dict[command]
next_position = tuple(map(sum, zip(position, direction)))
y, x = next_position
if -5 <= y <= 5 and -5 <= x <= 5:
check.add(tuple(sorted([position, next_position])))
position = next_position
return len(check)