728x90
🔗Problem Link
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
❔Thinking
- (0,0) 좌표에서 시작해서 'LRUD'로 이루어진 문자열 명령어에 따라 이동한다.
- (-5,5) 좌표 안에서 이동한 길이를 출력하되, 이미 지나친 길을 제외하고 출력한다.
- 경계를 벗어나는 명령어는 무시하며, 이미 지나친 길은 길이에서 제외될 뿐 이동은 한다.
💻Solution
def solution(dirs):
answer = 0
x,y = 0,0
visited = []
opposite_dir_dict = {'L':'R', 'R':'L', 'U':'D', 'D':'U'}
directions_dict = {'L':[-1,0], 'R':[1,0], 'U':[0,1], 'D':[0,-1]}
for d in dirs:
nx = x + directions_dict[d][0]
ny = y + directions_dict[d][1]
if -5<=nx<=5 and -5<=ny<=5:
if (d, nx, ny) not in visited or (opposite_dir_dict[d], x, y) not in visited:
visited.append((d,nx,ny))
visited.append((opposite_dir_dict[d], x, y))
answer += 1
x, y = nx, ny
return answer
🗝️keypoint
- 좌표가 아닌 경로에 대한 방문 여부를 확인해야한다.
- 경로는 (목적지, 방향), (출발지, 목적지) 등으로 표현할 수 있다.
if (d, nx, ny) not in vistied ~
if (x, y, nx, ny) not in vistied ~
'코딩테스트 > Python' 카테고리의 다른 글
[Baekjoon] 1439번 - 뒤집기 (0) | 2022.09.27 |
---|---|
[Programmers] Level 2. 모음사전 (0) | 2022.09.27 |
[Programmers] Level 2. 파일명 정렬 (1) | 2022.09.27 |
[LeetCode] 409. Longest Palindrome (0) | 2022.09.26 |
[Programmers] Level 2. 땅따먹기 (0) | 2022.09.25 |