본문 바로가기
대딩/프로그래머스풀이

[프로그래머스 lvl1] 크레인인형뽑기게임 풀이

by 경아ㅏ 2022. 3. 14.

해설

인형을 꺼내는 칸 번호를 입력 받을 때마다 인형을 뽑는다.

인형이 없을 경우에는 아무 처리 없이 넘어가고, 뽑힌 인형이 최근에 뽑은 인형과 동일하다면 해당 인형들을 삭제하고 결과값(터뜨린 인형 수)에 2를 더한다. 뽑힌 인형이 최근 인형과 다르다면 그냥 스택에 넣어주면 된다.

 

 

전체 코드

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <tuple>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <climits>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;
using ii = pair<int, int>;
using iii = tuple<int, int, int>;

#define X first
#define Y second

int take(vector<vector<int>>& board, const int& c) {
    
    int r = 0;
    int sz = board.size();

    //행에 있는 값이 0일 때까지 전진
    while (r < sz && !board[r][c]) r++; 
    
    //행에 있는 모든 값이 0인 경우 인형이 없는 것이므로 0 리턴
    if (r >= sz) return 0;

    //가장 위에 있는 인형의 값 리턴
    int tmp = board[r][c];
    board[r][c] = 0;
    return tmp;
}

int solution(vector<vector<int>> board, vector<int> moves) {

    int ret = 0;
    stack<int> st;

    for (auto x : moves) {

        //x칸에서 인형 뽑기
        int d = take(board, x-1);

        //인형이 없는 경우
        if (!d) continue; 

        //이전에 뽑은 인형과 동일한 경우
        if (!st.empty() && st.top() == d) { 
            ret += 2;
            st.pop();
            continue;
        }

        //이전에 뽑은 인형과 동일하지 않은 경우
        st.push(d); 
    }
    return ret;
}

댓글