개발하는 kim-hasa

[c++][프로그래머스] 크레인 인형뽑기 게임 본문

Algorithm/Programmers(c++)

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

kim-hasa 2021. 7. 27. 15:46

https://programmers.co.kr/learn/courses/30/lessons/64061

 

코딩테스트 연습 - 크레인 인형뽑기 게임

[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] [1,5,3,5,1,2,1,4] 4

programmers.co.kr

뽑아서 같은 경우 제거하는 애니팡같은 룰의 문제입니다.

 

먼저 변수를 지정하고, moves 벡터에서 하나씩 가져옵니다.

 

맨 위부터 한칸씩 내려가면서 인형이 있는 칸(0이 아닌 칸)을 찾고, 만약 모든 칸이 0이라면 다음으로 넘어갑니다.

 

인형을 뽑았다면, 버켓에 넣습니다. 이때 버켓에 아무것도 없으면 추가합니다.

 

만약 버켓이 비어있지 않고, 버켓의 마지막 인형과 넣을 인형이 같다면 버켓에서 그 인형을 제거합니다.

그리고 인형이 2개 제거되므로 answer의 값을 2 증가시킵니다.

 

버켓의 마지막 인형과 넣을 인형이 다르다면, 버켓에 인형을 추가합니다.

 

count 값으로 버켓의 마지막 index를 가르키도록 합니다.

#include <string>
#include <vector>

using namespace std;

int solution(vector<vector<int>> board, vector<int> moves) {
    int answer = 0;
    vector<int> bucket;     // 바구니 벡터
    int height;             // 높이를 체크
    int width;             // n번째 칸
    int count = -1;
    int max = board.size(); // 최대 길이
    int maxcount = 0;           // 최대 길이일 경우를 나타냄
    for(int i=0; i<moves.size(); i++)
    {
        width = moves[i] - 1;
        height = 0;
        
        while(board[height][width] == 0)    // 한개씩 내려가면서 인형 찾음
        {
            height++;
            if(height == max)   // 모든 칸이 0인 경우
            {
                maxcount = 1;
                break;
            }
        }
        
        if(maxcount == 1)   // 0인경우 다음 뽑기로
        {
            maxcount = 0;
            break;
        }
        else
        {
                
            if(bucket.size() != 0 && bucket[count] == board[height][width])
            {   // size가 0이 아니고, bucket 안에 있는 것과 뽑은 인형 비교
                // 둘이 동일한 경우 bucket에서 제거 및 answer count 증가
                bucket.pop_back();
                count--;
                answer += 2;
            }
            else
            {   // 동일하지 않은 경우, bucket이 비어있는 경우 추가
                bucket.push_back(board[height][width]);
                count++;
            } 
            board[height][width] = 0;   // 뽑은 위치 0으로
        } 
    }
    return answer;
}

※ 코드가 지저분할 수 있습니다.