본문 바로가기
알고리즘/자료구조

크레인 인형뽑기 게임

by e-pd 2020. 9. 9.

 

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.*;
class Solution {
    public int solution(int[][] boards, int[] moves) {
        int cnt = 0;   
        Stack<Integer> stack = new Stack<>();
        /*
        * 1. 각자리에 인덱스로 값을 꺼내온다.
          2. 스택에 넣는다
          3. 스택에 peek해서 같은 값이면 cnt +한다.
        */
        for (int move : moves) {
            int index = move -1;
            
            // 전체 배열에서 하나씩 꺼낸다.
            for (int[] board : boards) {
                int doll = board[index];
                if (doll > 0) {
                    
                    if (!stack.isEmpty() && stack.peek() == doll){
                        stack.pop();
                        cnt += 2;
                    } else {
                        stack.push(doll);    
                    }
                    board[index] = 0;
                    // 다음배열은 검사하지않게 break
                    break;
                }
            }
        }
         
        return cnt;
    }
}
cs

moves를 살펴보면 index에 +1 한값이라는 것을 알수있다. 

board를 하나씩 꺼내와서 인덱스에 해당하는 값과 stack의 값을 비교한다.

있으면 pop으로 제거, 없으면 스택에 넣는다. 

'알고리즘 > 자료구조' 카테고리의 다른 글

2차원 Array, List로 변경하기  (0) 2021.03.10
네트워크  (0) 2020.09.06
올바른 괄호  (0) 2020.08.06