최단거리라길래 BFS로 박치기 했는데 그게 아니었다. 최단거리로 가능 경로를 구하는게 아니고 단순 맨해튼 거리(x와 y 길이 절댓값의 합)로 더 가까운 위치를 구하기만 하면 되는 것이다.
아직 level1이니 너무 복잡하게 생각할 필요 없다.
#include <string>
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
int find_distance(pair<int, int> &have_to_push, pair<int, int> &finger){
int distance = 0;
//사방으로 한칸씩 밖에 이동 못함
//그러므로 거리는 x축 거리 + y축 거리임
distance = abs(have_to_push.first - finger.first) + abs(have_to_push.second - finger.second);
return distance;
}
string solution(vector<int> numbers, string hand) {
string answer = "";
int i, j;
int left_finger = 10, right_finger = 11;//최초 위치 초기화, 어차피 처음 한번씩만 사용
int L_distance, R_distance;
vector<pair<int, int>> keypad {{3, 1},
{0, 0},{0, 1},{0, 2},
{1, 0},{1, 1},{1, 2},
{2, 0},{2, 1},{2, 2},
{3, 0},{3, 2}//최초 위치 초기화
};
int current_num;
for(i = 0; i < numbers.size(); i++){
current_num = numbers[i];
switch(current_num){
case 1: case 4: case 7://왼손가락으로 클릭
left_finger = current_num;
answer += 'L';
break;
case 3: case 6: case 9://오른손가락으로 클릭
right_finger = current_num;
answer += 'R';
break;
default:
//keypad[current_num]와 left_finger_location, right_finger_location간의 거리 파악하고 L, R 지정
L_distance = find_distance(keypad[current_num], keypad[left_finger]);
R_distance = find_distance(keypad[current_num], keypad[right_finger]);
cout << current_num << "을 누르기 전 왼손가락의 거리 : " << L_distance << " / 오른손가락의 거리 : " << R_distance << "\n";
if(L_distance == R_distance){//주 손가락으로 누르기
cout << " 거리 같음 : ";
if(hand == "left"){ //왼손잡이
answer += 'L';
left_finger = current_num;
cout << "왼손가락으로 누름\n";
}
else{ //오른손잡이
answer += 'R';
right_finger = current_num;
cout << "오른손가락으로 누름\n";
}
}
//더 가까운 손가락으로 누르기
else if(L_distance < R_distance){//왼손가락으로 누르기
answer += 'L';
left_finger = current_num;
cout << " 거리 다름 : 왼손가락으로 누름\n";
}
else{//오른손가락으로 누르기
answer += 'R';
right_finger = current_num;
cout << " 거리 다름 : 오른손가락으로 누름\n";
}
break;
}
}
return answer;
}