[프로그래머스] 크레인 인형뽑기 게임(C++)



#include <string>
#include <vector>
#include <map>
using namespace std;

int solution(vector<vector<int>> board, vector<int> moves) {
    int answer = 0;
    
    map<int,vector<int>> temp;
    vector<int> temp_val;
    for(vector<int>::size_type i =0; i<board.size(); i++){
        for(vector<int>::size_type j =0; j<board[i].size();j++){
            temp_val.push_back(board[j][i]);
        }
        pair<int, vector<int>> temp_pair(i+1,temp_val);
        temp_val.clear();
        temp.insert(temp_pair);
    }
    vector<int> temp_answer;
    for (vector<int>::size_type i = 0; i < moves.size(); i++) 
	{
		for (vector<int>::size_type j = 0; j < temp[moves[i]].size(); j++) 
		{
			if (temp[moves[i]][j] == 0) continue;

			temp_answer.push_back(temp[moves[i]][j]);
			temp[moves[i]].erase(temp[moves[i]].begin() + j);
			if (temp_answer.size() == 1) {
				break;
			}
			if (temp_answer[temp_answer.size() - 1] == temp_answer[temp_answer.size() - 2]) {
				answer += 2;
				temp_answer.erase(temp_answer.begin() + (temp_answer.size() - 1));
				temp_answer.erase(temp_answer.begin() + (temp_answer.size() - 1));
			}
			break;
		}
	}
    
    return answer;
}

이번 문제는 1개의 열마다 움직이면서 숫자를 꺼내야하기 때문에 기존에 있던 board 벡터를 나누어서 다른 자료구조에 집어넣는게 중요하다. 위 코드를 예시로 들면 map<int,vector<int>> temp;처럼 말이다. map 컨테이너를 선택한 이유는 매개변수로 주어진 moves 벡터가 각 열에 고유 id로 이루어져 있기 때문에 map컨테이너를 선택하였다. 그리고 temp_answer 컨테이너로 moves 컨테이너 원소의 해당하는 열의 가서 숫자를 꺼내서 집어넣은 다음 바로 temp_answer의 이전 원소와 비교하여 같은 원소라면 둘 다 지우고 answer의 값을 2증가 시킨다.




© 2022. by KSC

Powered by sora