풀이 과정
1. 최대 길이가 -55이므로.. 현재 위치를 (5,5)로 두고 010으로 제한한다.
2. 방문 체크를 위해 set을 사용. set에는 리스트를 넣을수 없어서 Tuple로 변환하여 set에 넣어준다.
=> (현재x, 현재y, 이동x, 이동y)
=> (이동x, 이동y, 현재x, 현재y)
* 처음 걸어본 길의 길이이므로 이동한 길을 통해 반대에서 이곳으로 돌아오는 케이스도 있기 때문에 두가지 케이스를 넣어준다.
3. 길이 막혀있는지, 막혀있지 않다면 방문한 길인지를 체크하면서 처음 걸어본 길의 길이를 1씩 증가시킨다.
def solution(dirs):
answer = 0
path = set()
pos = [5, 5]
for d in dirs:
if d == 'U' and pos[0] > 0:
if tuple([pos[0], pos[1], pos[0]-1, pos[1]]) not in path:
path.add(tuple([pos[0], pos[1], pos[0]-1, pos[1]]))
path.add(tuple([pos[0]-1, pos[1], pos[0], pos[1]]))
answer += 1
pos[0] -= 1
elif d == 'L' and pos[1] > 0:
if tuple([pos[0], pos[1], pos[0], pos[1]-1]) not in path:
path.add(tuple([pos[0], pos[1], pos[0], pos[1]-1]))
path.add(tuple([pos[0], pos[1]-1, pos[0], pos[1]]))
answer += 1
pos[1] -= 1
elif d == 'R' and pos[1] < 10:
if tuple([pos[0], pos[1], pos[0], pos[1]+1]) not in path:
path.add(tuple([pos[0], pos[1], pos[0], pos[1]+1]))
path.add(tuple([pos[0], pos[1]+1, pos[0], pos[1]]))
answer += 1
pos[1] += 1
elif d == 'D' and pos[0] < 10:
if tuple([pos[0], pos[1], pos[0]+1, pos[1]]) not in path:
path.add(tuple([pos[0], pos[1], pos[0]+1, pos[1]]))
path.add(tuple([pos[0]+1, pos[1], pos[0], pos[1]]))
answer += 1
pos[0] += 1
return answer
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
'알고리즘[Python] > 프로그래머스' 카테고리의 다른 글
[ Lv 2 ] [3차] 방금그곡 (0) | 2021.07.03 |
---|---|
[ Lv 2 ] 피보나치 수 (0) | 2021.07.01 |
[ Lv 2 ] 쿼드압축 후 개수 세기 (0) | 2021.06.30 |
[ Lv 2 ] 스킬트리 (0) | 2021.06.29 |
[ Lv 2 ] 이진 변환 반복하기 (0) | 2021.06.29 |