ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/64061?language=java 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ’€์ด]

์Šคํƒ์„ ์ด์šฉํ•˜์—ฌ ํ’€์ด๋ฅผ ์ง„ํ–‰ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

๋งŒ์•ฝ board์˜ ํฌ๊ธฐ๊ฐ€ N ์ด๋ผ๋ฉด, N + 1 ํฌ๊ธฐ์˜ ์Šคํƒ๋ฐฐ์—ด Stack์„ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.

1~N๊นŒ์ง€ ์ธํ˜•๋ฝ‘๊ธฐ ๊ธฐ๊ณ„ ๋ชจ์–‘์„ stack[1] ~ stack[N] ์— ์ €์žฅํ•˜๊ณ , ๋ฝ‘ํžŒ ์ธํ˜•๋“ค์„ ๋‹ด๋Š” ์ž„์‹œ stack์€ stack[0]์„ ์ด์šฉํ•ฉ๋‹ˆ๋‹ค.

 

์Šคํƒ์€ FIFO์˜ ํŠน์„ฑ์„ ์ง€๋‹ˆ๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— for๋ฌธ์„ ํ†ตํ•ด ์Šคํƒ์— board๋ฐฐ์—ด์˜ ๋ฐ‘์ค„๋ถ€ํ„ฐ ์ฐจ๋ก€๋กœ ์ธํ˜• number๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.์ด๋•Œ, ๋งŒ์•ฝ 0์ด๋ผ๋ฉด ์นธ์ด ๋น„์–ด์žˆ์œผ๋ฏ€๋กœ continueํ•ด์ค๋‹ˆ๋‹ค.

 

๊ทธ๋‹ค์Œ, moves๋ฐฐ์—ด ํฌ๊ธฐ๋งŒํผ pick()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์ธํ˜•์„ ํ•œ๊ฐœ์”ฉ ๋ฝ‘์•„์ค๋‹ˆ๋‹ค.

pick() ํ•จ์ˆ˜์— ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ธํ˜•์นธ์˜ index์ธ moves์˜ ์ˆซ์ž๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ํ•ด๋‹น์ค„์—์„œ ์ธํ˜•์„ ๋ฝ‘์•„ ์ž„์‹œ stack์— pushํ•ฉ๋‹ˆ๋‹ค.

์ด๋•Œ, push๋ฅผ ์ง„ํ–‰ํ•˜๊ธฐ์— ์•ž์„œ ์ž„์‹œ stack์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์„ peekํ•˜์—ฌ ๋งŒ์•ฝ ๋ฝ‘ํžŒ ์ธํ˜•๊ณผ ๊ฐ™๋‹ค๋ฉด ์ƒ์‡„ํ•˜๊ณ  answer๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๊ณ  ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด ๊ทธ๋Œ€๋กœ pushํ•ฉ๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

import java.util.*;
class Solution {
    private static Stack<Integer> stack[]; // 0์€ ๋ฝ‘์•„์„œ ์ €์žฅํ•˜๋Š”๊ณณ, 1 ~ N์€ ๋ฝ‘๊ธฐ ๊ธฐ๊ณ„
    private static int answer = 0;
    public int solution(int[][] board, int[] moves) {
        int N = board.length;
        stack = new Stack[N + 1];
        for(int i=0;i<=N;i++) {
            stack[i] = new Stack<Integer>();
        }
        for(int i=N-1;i>=0;i--) {
            for(int j=0;j<N;j++) {
                if(board[i][j] == 0) {
                    continue;
                }
                stack[j+1].push(board[i][j]);
            }
        }
        for(int i=0;i<moves.length;i++) {
            pick(moves[i]);
        }
        return answer;
    }
    public static void pick(int index) {
        if(stack[index].isEmpty()) {
            return;
        }
        int p = stack[index].pop();
        if(stack[0].isEmpty()) {
            stack[0].push(p);
            return;
        }
        if(stack[0].peek() == p) {
            stack[0].pop();
            answer += 2;
            return;
        }
        stack[0].push(p);
    }
}