-
[프로그래머스] 방문 길이알고리즘 2023. 7. 9. 00:59728x90
1. 문제
https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
2. 접근
1. 처음 시작지점을 x,y로 받고, a ( 문제에서는 dirs ) 에서 나오는 방향에 따라서 -5<=x,y<=5 를 넘지 않는지 확인하면서, 중복 확인해서 answer에 넣어준다 [ 중복확인은 not in 이나 set() 쓰기 ]
주의
- 현 x,y 좌표만 넣으면 안된다. [ test case 1번 같은 경우 같은 좌표로 돌아오는 포인트가 있는데 그러면 선분이 아니기에 카운트가 안됨 ]
- 현 x,y 좌표랑 next_x, next_y 좌표도 넣어줘야 한다
- 또한 -> 이 방향이나 <- 이 방향이나 좌표가 같으면 선분은 같으니까 answer에 2개다 넣어준다
2. 마지막에 answer에 2개씩 넣어줬으니까 //2 해주기
3. 풀이
def solution(a): x,y = 0,0 answer = [] for direction in a: if (direction == 'U') and (-5<=y<=4 and -5<=x<=5): next_x = x next_y = y + 1 if [x,y,next_x,next_y] not in answer: answer.append([x,y,next_x,next_y]) answer.append([next_x,next_y,x,y]) elif (direction == 'L') and (-5<=y<=5 and -4<=x<=5): next_x = x - 1 next_y = y if [x,y,next_x,next_y] not in answer: answer.append([x,y,next_x,next_y]) answer.append([next_x,next_y,x,y]) elif (direction == 'R') and (-5<=y<=5 and -5<=x<=4): next_x = x + 1 next_y = y if [x,y,next_x,next_y] not in answer: answer.append([x,y,next_x,next_y]) answer.append([next_x,next_y,x,y]) elif (direction == 'D') and (-4<=y<=5 and -5<=x<=5): next_x = x next_y = y - 1 if [x,y,next_x,next_y] not in answer: answer.append([x,y,next_x,next_y]) answer.append([next_x,next_y,x,y]) x = next_x y = next_y return len(answer) // 2
'알고리즘' 카테고리의 다른 글
[프로그래머스] 점 찍기 (0) 2023.07.11 [프로그래머스] n^2 배열 자르기 (0) 2023.07.11 [프로그래머스] 의상 (0) 2023.07.08 [프로그래머스] 전화번호 목록 (0) 2023.06.29 [프로그래머스] 튜플 (0) 2023.06.29