본문 바로가기
알고리즘

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

by irerin07 2020. 4. 3.
728x90

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

코드: https://github.com/irerin07/AlgorithmStudyBaek/blob/master/src/programmers_lvl_1/programmers64061.java

 

import java.util.Iterator;
import java.util.Stack;

public class programmers64061 {
    public static void main(String[] args) {
        int[][] board = new int[][]{
                {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}};
        int[] moves = new int[]{1, 5, 3, 5, 1, 2, 1, 4};
        System.out.println(solution(board, moves));

    }

    public static int solution(int[][] board, int[] moves) {
        int answer = 0;
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < moves.length; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[j][moves[i] - 1] != 0) {
                    //해당 위치에 인형이 있는 경우
                    if (st.empty()) {
                        //인형을 담을 스택이 비어있는 경우
                        st.push(board[j][moves[i] - 1]);
                    } else {
                        //스택이 비어있지 않는 경우
                        if (st.peek() == board[j][moves[i] - 1]) {
                            //st.peek()을 사용하여 집어올린 인형과 값을 비교해 두 값이 같은 경우에는
                            st.pop();
                            //스택에서 인형을 제거한 뒤
                            answer += 2;
                            // answer를 2 증가시켜준다. (인형 2개가 사라지기 때문)
                        } else {
                            //st.peek()을 사용하여 집어올린 인형과 값을 비교해 두 값이 다른 경우에는
                            st.push(board[j][moves[i] - 1]);
                            //스택에 인형을 넣어준다.
                        }
                    }
                    //일련의 작업이 끝난 뒤 인형을 집어올린 좌표에는 더 이상 인형이 없으므로 0을 저장한다.
                    board[j][moves[i] - 1] = 0;
                    break;
                }
            }
        }
        return answer;
    }
}

 

단순한 문제

이중 for loop을 사용하여 인형을 끄집어 올리고 

스택이 비어있다면 인형을 담고,

비어있지 않은 스택에는 담을때마다 peek()메서드를 사용해서

집어올린 인형과 스택 제일 위에 있는 인형이 같은지 확인하고

두 인형이 같다면 pop()메소드를 통해 스택 제일 위에 있는 인형을 빼서

answer에 2를 더해주고(같은 인형끼리 쌓이면 두 인형이 모두 사라지기때문)

다르다면 스택에 인형을 추가하는 작업을 통해 문제를 풀었다.

 

728x90