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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/PythonํŒŒ์ด์ฌ] ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„

meeeeejin 2021. 5. 15. 10:45

๋ฌธ์ œ ๋งํฌ: https://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

 

 

๋ฌธ์ œ ์„ค๋ช…

board์™€ moves์˜ ์ •๋ณด๋กœ ํฌ๋ ˆ์ธ ์ž‘๋™์„ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ํ•ฉ๋‹ˆ๋‹ค. ์ด๋•Œ ๋ฐ”๊ตฌ๋‹ˆ๋Š” stack์œผ๋กœ ๊ตฌํ˜„ํ•˜์—ฌ ๋งŒ์•ฝ ํ˜„์žฌ ๋ฝ‘์€ ์ธํ˜•์ด stack top์˜ ์ธํ˜•๊ณผ ๊ฐ™์€ ์ข…๋ฅ˜๋ผ๋ฉด ์ธํ˜•์„ ์—†์• ์•ผ ํ•ฉ๋‹ˆ๋‹ค. 

 

  1. doll์— ํ˜„์žฌ ํฌ๋ ˆ์ธ ์ž‘๋™์— ๋ฝ‘ํž ์ธํ˜•์˜ ๋ฒˆํ˜ธ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  2. ๋งŒ์•ฝ doll == 0์ด๋ฉด ๋ฝ‘ํž ์ธํ˜•์ด ์—†์œผ๋ฏ€๋กœ ๋‹ค์Œ ํฌ๋ ˆ์ธ ์ž‘๋™์œผ๋กœ ๋„˜์–ด๊ฐ‘๋‹ˆ๋‹ค. 
  3. doll์ด ๋ฐ”๊ตฌ๋‹ˆ์— ์ œ์ผ ์œ„์— ์žˆ๋Š” ์ธํ˜•(stack top)๊ณผ ๊ฐ™์€ ์ข…๋ฅ˜๋ผ๋ฉด doll์„ ๋ฐ”๊ตฌ๋‹ˆ์— ๋„ฃ์ง€์•Š๊ณ , stack top๋„ pop ํ•ฉ๋‹ˆ๋‹ค. 
  4. ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ doll์„ ๋ฐ”๊ตฌ๋‹ˆ์— pushํ•ฉ๋‹ˆ๋‹ค. 
  5. moves์˜ ๋ชจ๋“  ์›์†Œ์— ๋Œ€ํ•ด 1~4๋ฅผ ๋ฐ˜๋ณต ์ˆ˜ํ–‰ํ•˜๋ฉฐ ์‚ฌ๋ผ์ง„ ์ธํ˜•์˜ ๊ฐœ์ˆ˜๋ฅผ ์…‰๋‹ˆ๋‹ค. 

 

 

 

 

์†Œ์Šค์ฝ”๋“œ

def solution(board, moves):
    answer = 0
    stack = []      # ๋ฐ”๊ตฌ๋‹ˆ

    for move in moves:
        doll = 0
        # ํ˜„์žฌ ํฌ๋ ˆ์ธ ์ž‘๋™์— ๋ฝ‘ํž ์ธํ˜•์˜ ๋ฒˆํ˜ธ ๊ตฌํ•˜๊ธฐ
        for i in range(len(board)):
            if board[i][move-1] != 0:
                doll = board[i][move-1]
                board[i][move-1] = 0
                break
        if doll == 0: continue # ๋ฝ‘ํž ์ธํ˜•์ด ์—†๋‹ค๋ฉด ๋‹ค์Œ ํฌ๋ ˆ์ธ ์ž‘๋™์œผ๋กœ ๋„˜์–ด๊ฐ
        
        if stack and stack[-1] == doll: # ๋ฐ”๊ตฌ๋‹ˆ์— ๊ฐ™์€ ์ธํ˜•์ด ์—ฐ์†ํ•ด์„œ ์Œ“์ผ ๊ฒฝ์šฐ
            answer += 2
            stack.pop()
        else:
            stack.append(doll)
    
    return answer

 

 

 

 

 

728x90