알고리즘/c++ 프로그래머스
[프로그래머스 키패드 누르기] c++ (풀이, 코드)
말린밴댕이_공부
2023. 7. 4. 09:29
반응형
문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/67256
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제
코드, 풀이
처음에 풀이를 가로^2 + 세로^2을 거리로 생각을 해서 (문제를 제대로 읽어야지 바보야..) 처음에 틀렸었습니다.
문제는 10분 정도 내외의 시간이 걸렸습니다.
좌표값이라고 생각을 하고 0,0기준으로 y,x좌표를 추출하였습니다.
y = (numbers[i] - 1) / 3; x = (numbers[i] - 1) % 3;
1,4,7의 경우에는 왼쪽에 대한 map을 갱신
3,6,9의 경우에는 오른쪽에 대한 map을 갱신
2,5,8,0의 경우에는 가까운 거리에 대한 손을 갱신 같을경우 손잡이 판별.
간단한 문제다보니 알고리즘에 생각과 고민보다는 코드를 우다다다 치는 시간이 더 걸린 문제였다고 생각합니다
#include <string>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
map <string,pair<int,int>> handMap; //handMap으로 왼쪽 오른쪽 현재 위치 파악
//left -> true right -> false
bool leftCheck(int y, int x,bool isLeft){
int left = abs(handMap["left"].first - y) + abs(handMap["left"].second - x);
int right = abs(handMap["right"].first - y) + abs(handMap["right"].second - x);
if(left < right){
return true;
}else if(left > right){
return false;
}else{
if(isLeft)
return true;
else
return false;
}
}
string solution(vector<int> numbers, string hand) {
string answer = "";
//왼손,오른손 잡이 판별
bool isLeft = 1;
if(hand == "right")
isLeft = 0;
//처음 *과 #에 있으므로 위치 설정
handMap["left"] = {3,0};
handMap["right"] = {3,2};
for(int i = 0; i < numbers.size();i++){
int y = (numbers[i] - 1) / 3; // y좌표
int x = (numbers[i] - 1) % 3; // x좌표
if(numbers[i] == 0){
y = 3;
x = 1;
}
if(numbers[i] == 1|| numbers[i] == 4||numbers[i] == 7){
answer+= "L";
handMap["left"] = {y,x}; // 높이 위치 파악
}else if(numbers[i] == 3||numbers[i] == 6||numbers[i] == 9){
answer+="R";
handMap["right"] = {y,x};
}else{
bool left = leftCheck(y,x,isLeft);
if(left){
answer+="L";
handMap["left"] = {y,x};
}else{
answer += "R";
handMap["right"] = {y,x};
}
}
}
return answer;
}
반응형