반응형

문제 링크

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

풀이 )

  세로를 x축, 가로를 y축으로 사용했다.

  먼저 입력된 숫자의 좌표를 cx, cy에 넣었다.

  • 1, 4, 7(numbers[i]%3 == 1)인 경우 'L'을 출력하고 왼손을 현재 숫자의 좌표로 옮긴다.
  • 3, 6, 9(numbers[i] > 0 && numbers[i]%3 == 0)인 경우 'R'을 출력하고 오른손을 현재 숫자의 좌표로 옮긴다.
  • 나머지에 대해서는 현재 양 손의 위치와 숫자의 거리를 측정하여
    • 더 가까운 손이 있는 경우, 더 가까운 손으로 입력을 하고
    • 두 손의 거리가 같은 경우, 왼손잡이는 왼손으로, 오른손잡이는 오른손으로 입력한다.

 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int lx = 3, ly = 0, rx = 3, ry = 2;
int cx, cy, dl, dr;
string answer;

void rHand(void){
    answer += 'R';
    rx = cx; ry = cy;
}

void lHand(void){
    answer += 'L';
    lx = cx;
    ly = cy;
}

string solution(vector<int> numbers, string hand) {
    int len = numbers.size();
    for(int i = 0; i < len; ++i){
        if(numbers[i] == 0){
            cx = 3;
            cy = 1;
        }
        else{
            cx = (numbers[i]-1)/3;
            cy = (numbers[i]-1)%3;
        }
        
        if(numbers[i]%3 == 1)
            lHand();
        else if(numbers[i] && numbers[i]%3 == 0)
            rHand();
        else{
            dl = abs(cx-lx)+abs(cy-ly);
            dr = abs(cx-rx)+abs(cy-ry);
            if(dl < dr)
                lHand();
            else if(dl > dr)
                rHand();
            else{
                if(hand == "left")
                    lHand();
                else
                    rHand();
            }
        }
    }
    return answer;
}

 

주의 )

  키패드에서 0에 대한 처리

반응형

+ Recent posts