코딩테스트

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

mhui123 2025. 4. 5. 11:42
반응형

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

문제

board는 인형뽑기기계의 내부 상황이다. 기계 맨 위 ~ 맨 아래까지를 순서대로 표현하고 있으며

0 은 빈 공간, 1 ~ 100 은 인형의 종류를 의미한다.

moves는 뽑은 열의 집합이다.

뽑은 인형 == 직전에 뽑은 인형일 경우 두 인형을 제거한다.

board에 moves대로 진행하였을 때 총 제거된 인형의 수를 구하시오.

접근

뽑은 인형을 쌓아두고 마지막 인형 == 뽑은 인형인지 파악하기 위해 Stack을 사용했다.

public int solution(int[][] board, int[] moves) {
        Stack<Integer> catched = new Stack<>();
        int answer = 0;

        for(int move : moves){
            int col = move -1;
            for (int[] row : board) {
                int doll = row[col] == 0 ? 0 : row[col];
                if (doll > 0) {
                    if (!catched.isEmpty() && catched.get(catched.size() - 1) == doll) {
                        catched.pop();
                        answer ++;
                    } else {
                        catched.push(doll);
                    }
                }
            }
        }

        return answer;
    }

발견된 문제

1. 없앤 인형의 수가 아닌 없앤 횟수를 세어 기대값과 다른 값이 도출됨.
2. 인형을 뽑고 바로 다음 move를 수행하지 않아 기대와는 다른 결과가 도출됨.
3. 인형을 뽑고나서 board를 갱신하지 않아 예상과 다른 결과가 도출됨.

수정

public static int solution(int[][] board, int[] moves) {
        Stack<Integer> catched = new Stack<>();
        int answer = 0;

        for(int move : moves){
            int col = move -1;
            for (int[] row : board) {
                if(row[col] != 0){
                    int doll = row[col];
                    row[col] = 0; // 뽑은 인형 제거

                    if (!catched.isEmpty() && catched.peek() == doll) {
                        catched.pop();
                        answer += 2;
                    } else {
                        catched.push(doll);
                    }

                    break;
                }
            }
        }

        return answer;
    }

알게된 점

catched.get(catched.size() - 1) == doll 과 catched.peek() == doll은 동일한 의미이다.
반응형