๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Programmers

[Programmers] ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„

 

 

๋‚˜์˜ ์ฝ”๋“œ 

 

def solution(board, moves):
    stack = []
    answer = []
    imp = []
    cnt = 0
    
    # ๋นˆ์นธ์„ ์ œ์™ธํ•˜์—ฌ ๋‚จ์€ ์ธํ˜•๋งŒ ๋‚จ๊ธด ์ƒˆ๋กœ์šด ๋ฐฐ์—ด ๋งŒ๋“ ๋‹ค. 
    for i in range(len(board)):
        for t in range(len(board)):
            if board[t][i] != 0:
                stack.append(board[t][i])
        stack.reverse()
        answer.append(stack)
        stack = []
    
    # ์ธํ˜•์„ ์ƒˆ๋กœ์šด ๋ฐ”๊ตฌ๋‹ˆ์— ๋„ฃ์œผ๋ฉด์„œ ๋งˆ์ง€๋ง‰ ์›์†Œ์™€ ๊ทธ ์ „ ์›์†Œ๊ฐ€ ๊ฐ™์œผ๋ฉด pop ์‹œํ‚จ๋‹ค. 
    # cnt ๋Š” ์ธํ˜•์ด ์‚ฌ๋ผ์ง€๋Š” ํšŸ์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์— ์‚ฌ๋ผ์ง„ ์ธํ˜•์˜ ๊ฐœ์ˆ˜๋Š” ์ด ๊ฐ’์˜ 2๋ฐฐ์ด๋‹ค. 
    for l in moves:
        if len(answer[l-1]) > 0:
            imp.append(answer[l-1].pop())
            if len(imp) > 1:
                if imp[-1] == imp[-2]:
                    imp.pop()
                    imp.pop()
                    cnt += 1
        if len(answer[l-1]) == 0:
            continue
    return cnt * 2
๋ถ„์„ > ์šฐ์„  0์ด ์žˆ์œผ๋ฉด ์›์†Œ๋ฅผ ๋บ„ ๋•Œ ๋ถˆํŽธํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ ์„ธ๋กœ์ค„์— ๋‚จ์•„์žˆ๋Š” ์ธํ˜•๋“ค๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด answer์„ ๋งŒ๋“ค์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด ๋ฐฐ์—ด์„ ๊ฐ€์ง€๊ณ  imp ๋ผ๋Š” ์ƒˆ๋กœ์šด ๋ฐ”๊ตฌ๋‹ˆ์— ์›์†Œ๋ฅผ ๋„ฃ์œผ๋ฉด์„œ, imp์˜ ๋งˆ์ง€๋ง‰ ์›์†Œ์™€ ๊ทธ ์ „ ์›์†Œ๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ pop์„ ์‹œํ‚ค๊ณ  ๊ทธ ํšŸ์ˆ˜ cnt ๋ฅผ ๊ตฌํ–ˆ๋‹ค. cnt ๋Š” ์‚ฌ๋ผ์ง„ ํšŸ์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์— ์‹ค์ œ ์‚ฌ๋ผ์ง„ ์ธํ˜•์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด cnt ๊ฐ’์— 2๋ฐฐ๋ฅผ ๊ณฑํ•œ ๊ฐ’์€ ๋ฐ˜ํ™˜ํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค. 

 

 

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„

[[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