프로그래머스 - 방문 길이

이서현·2021년 7월 29일
0

Algorithm

목록 보기
60/76

07.29에 푼 문제입니다🌷
방문 길이

풀이법

  1. 범위에 넘어가지 않는지 확인한다.
  2. 넘어가지 않으면 point를 이동한다.
  3. 이전 point와 현재 point를 string 으로 바꾼다.
    3.1 이전 point + 현재 point 가 stack에 있는지 확인
    3.2 현재 point + 이전 point 가 stack에 있는지 확인
    이렇게 2번 하는 이유는 왔다 갔다 한 점을 확인하기 위해서 이다.
    예를 들어 UDU 라고하면
    U : [0,0] -> [0,1] = 0001   stack = [0001]
    D : [0,1] -> [0,0] = 0100   stack = [0001, 0100]
    같은 경로지만 문자열로 앞뒤를 바꾸면 달라지기 때문에 예외가 발생한다.
  4. 두가지 문자열 모두 없을 경우 answer++, stack에 문자열 하나만 push한다.

전체 코드

function solution(dirs) {
    var answer = 0;
    const point=[0,0]
    const points= []
    
    for(let dir of dirs){
        let pointstr1 =String(point[0])+String(point[1])
        if(dir==='U'){
            if(point[1]+1>5) continue
            point[1]++
            checkpoints(pointstr1)
        }
        else if(dir==='D'){
            if(point[1]-1<-5) continue
            point[1]--
            checkpoints(pointstr1)
        }
        else if(dir==='R'){
            if(point[0]+1>5) continue
            point[0]++
            checkpoints(pointstr1)
        }
        else if(dir==='L'){
            if(point[0]-1<-5) continue
            point[0]--
            checkpoints(pointstr1)
        }
    }
    
    function checkpoints(pointstr1){
        let pointstr2=String(point[0])+String(point[1])
        if(!(points.includes(pointstr1+pointstr2)
               ||points.includes(pointstr2+pointstr1))){
            answer++
            points.push(pointstr1+pointstr2)
        }
    }
    
    return answer;
}
profile
안녕하세요. 이서현입니다( ღ'ᴗ'ღ )

0개의 댓글