홍시홍의 프로그래밍

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

알고리즘 문제풀이/프로그래머스

[프로그래머스] 크레인 인형뽑기

홍시홍 2020. 4. 3. 00:06

분류 : 구현

 

요구사항

stack 활용하여 문제가 끝난 후, 사라진 인형의 수 구하기

 

풀이

함정없는 단순 구현 문제이다

문제에 제시된 조건대로 구현하면 된다

 

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int map[35][35];
int boardr = 0;
int boardc = 0;

int solve(vector<int> move) {
    vector<int> v;
    int cnt = 0;
    for (int i = 0; i < move.size(); i++) {
        int nowc = move[i];
        int r = 0;
        for (r = 1; r <= boardr; r++) {
            if (map[r][nowc] != 0) {
                int temp = map[r][nowc];
                map[r][nowc] = 0;
                if (!v.empty()) {
                    int nowvalue = v.back();
                    if (temp == nowvalue) {
                        v.pop_back();
                        cnt++;
                        cnt++;
                       
                    }
                    else {
                        v.push_back(temp);
                    }
                }
                else {
                    v.push_back(temp);
                }
                break;
            }
        }
    }
    return cnt;
}
//board 2차원 배열, moves는 이동 배열
int solution(vector<vector<int>> board, vector<int> moves) {
    int answer = 0;
    boardr = board.size();
    boardc = board[0].size();

    //init
    for (int i = 0; i < board.size(); i++) {
        for (int j = 0; j < board[i].size(); j++) {
            map[i+1][j+1] = board[i][j];
        }
    }
    answer = solve(moves);
    return answer;
}
Comments