๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํฌ๋ ˆ์ธ ์ธํ˜• ๋ฝ‘๊ธฐ 2019 ์นด์นด์˜ค ๊ฐœ๋ฐœ์ž ๊ฒจ์šธ ์ธํ„ด์‰ฝ

by Jouureee 2021. 2. 24.

๐ŸŽฏ ๋ฌธ์ œ : 

 

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

 

๐Ÿงฉ๋ถ„์„ :

 

2๋…„์ „์— ๋งŒ๋‚ฌ๋˜ ๋ฌธ์ œ ..! 

์ง€๊ธˆ์€ ์ฝ”๋“œ ์ดํ•ด๊ฐ€ ๋‹คํ–‰์ด ๋˜์—ˆ๋‹ค. ์•ฝ๊ฐ„์˜ ๋ธ”๋กœ๊ทธ๋“ค์„ ์ฐธ๊ณ ํ–ˆ์ง€๋งŒ 

 

2์ฐจ์› board = vector<vector<int>> board

ํฌ๋ ˆ์ธ์˜ ์›€์ง์ž„ = vector<int> moves

 

1. ํฌ๋ ˆ์ธ์˜ ์›€์ง์ž„์ด ๋๋‚ ๋•Œ ๊นŒ์ง€ check ํ•  ์ธ๋ฑ์Šค๋ฅผ -1ํ•˜์—ฌ ์ ‘๊ทผ 

2. borad์˜ ํ•œ ํ–‰์”ฉ ๊ฒ€์‚ฌํ•˜๋ฉด์„œ ์›€์ง์ผ ์—ด(check ์ธ๋ฑ์Šค ๊ฐ’)์ด ๋นˆ์นธ(0)์ด ์•„๋‹ˆ๋ฉด

stack์— ์Œ“์ธ ๊ฐ’์ด ์—†์œผ๋ฉด push

stack์— ์Œ“์˜€๋Š”๋ฐ ๊ฐ’์ด ๊ฐ™์ง€ ์•Š์•„๋„ push

stack์— ์Œ“์˜€๋Š”๋ฐ ๋ฐ”๋กœ ์•ž์˜ ๊ฐ’์ด ๊ฒ€์‚ฌํ•œ ๋ฐฐ์—ด์˜ ๊ฐ’๊ณผ ๊ฐ™์œผ๋ฉด pop, ans += 2

๋ฐฐ์—ด์˜ ํ–‰ ๋‹ค ๋Œ๋ฉด break ๋ฌธ ํ†ตํ•ด ๋น ์ ธ ๋‚˜์˜จ๋‹ค.  

 

 

๐ŸŽฎ c++ ์ฝ”๋“œ :

#include <string>
#include <vector>
#include <stack>

using namespace std;

int solution(vector<vector<int>> board, vector<int> moves) {
    int answer = 0;
    stack<int> s;
    //moves๋Š” ์›€์ง์ผ ์—ด 
    for(int i = 0; i < moves.size(); i++){
        int check = moves[i] - 1;
        for(int j =0; j < board.size(); j++){
            if(board[j][check] !=0){
                //s์—๋Š” ๋‹ด๊ฒจ ํ„ฐํŠธ๋ฆด ๊ฒŒ ์—†์œผ๋ฏ€๋กœ 
                if(!s.empty() && s.top() == board[j][check]){
                    s.pop();
                    answer += 2;
                }else{
                    s.push(board[j][check]);
                }
                 board[j][check] = 0;
                break;
            }
        }
    }
    
    return answer;
}

๋Œ“๊ธ€