택시짱의 개발 노트

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

알고리즘

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

택시짱 2020. 4. 1. 15:14

링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

 

크레인을 모두 작동시킨 후 터트려져 사라진 인형의 개수 구하는 문제이다.

 

저는 queue와 stack을 이용하여 문제를 풀었습니다.

 

먼저 인형은 차곡차곡 쌓여 있기 때문에 바로 들어간 것이 바로 나오기 때문에 빨간색으로 이루어진 부분을

한 개의 queue로 만들었습니다. 그러면 총 5*5이니 5개의 queue가 만들어지겠네요

 

그리고 옆에 인형을 뽑아내는 부분을 stack으로 만들었습니다. 인형이 들어갈 때 항상 맨 위에 있는 인형과 비교를 해야 되기 때문입니다.

 

인형을 뽑아 stack에 넣고 stack의 top과 같다면 stack.pop을 해주고 cnt를 증가시켜주고

제거된 횟수에*2를 해주면 인형이 제거된 개수가 나오게 됩니다.

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<set>
#include<map>
#include<cstring>
#include<functional>
#include<cmath>
#include<stack>

#define SIZE 40
const int INF = 2000000000;

using namespace std;

typedef long long int ll;

stack<int> res;
queue<int> b_queue[SIZE];

int solution(vector<vector<int>> board, vector<int> moves) {
   int board_size = board.size();

   for (int j = 0; j < board_size; j++) {
      for (int i = 0; i < board_size; i++) {
         if(board[i][j] != 0)
            b_queue[j].push(board[i][j]);
      }
   }

   int cnt = 0;
   for (auto m: moves) {
      int move = m - 1;
      if (!b_queue[move].empty()) {
         int block = b_queue[move].front();
         b_queue[move].pop();

         if (res.empty()) {
            res.push(block);
         }
         else if(!res.empty()){
            if (res.top() == block) {
               res.pop();
               cnt++;
            }
            else if (res.top() != block) {
               res.push(block);
            }
         }
      }
   }
   
   return cnt * 2;
}
반응형

'알고리즘' 카테고리의 다른 글

[프로그래머스] 불량 사용자  (2) 2020.04.01
[프로그래머스] 튜플  (0) 2020.04.01
[백준] 5427번 불  (0) 2020.03.31
[백준] 17127번 벚꽃이 정보섬에 피어난 이유  (0) 2020.03.31
[백준] 13913번 숨바꼭질 4  (0) 2020.03.30
Comments