본문 바로가기

알고리즘

2020 카카오 인턴십>키패드 누르기

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/67256

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

나의코드

function solution(numbers, hand) {
  var answer = "";
  let left=10;
  let right=11;
  let distance=Number.MAX_SAFE_INTEGER;
  for (let i = 0; i < numbers.length; i++) {
    let v = numbers[i];
    if (v === 1 || v === 4 || v === 7) {
      answer += "L";
      left=v
    } else if (v === 3 || v === 6 || v === 9) {
      answer += "R";
      right=v
    }else{
      let left_dist=Math.min(calculateDist(left,v))
      let right_dist=Math.min(calculateDist(right,v))
      if(left_dist>right_dist){
        answer+="R"
        right=v
      }else if(left_dist<right_dist){
        answer+="L"
        left=v
      }else{
        if(hand==="left"){
          answer+="L"
           left=v
        }else{
          answer+="R"
           right=v
        }
      }
    }
  }
  return answer
}

function calculateDist(start,end){
  let graph=[[8,11,10],[2,4],[1,3,5],[2,6],[1,5,7],[2,4,6,8],[3,5,9],[4,8,10],[5,7,9,0],[6,8,11],[7,0],[9,0]]
  let visited=Array(12).fill(false)
  let temp=[]
  let distance=Number.MAX_SAFE_INTEGER;
  function DFS(start,end){
    if(start===end){ 
    distance=Math.min(distance,temp.length)
    }else{
      for(x of graph[start]){
        if(!visited[x]){
          visited[x]=true
          temp.push(x)
          DFS(x,end)
          temp.pop()
          visited[x]=false
        }
      }
    }
  }
  DFS(start,end)
  return distance
}
728x90