STUDYING/Algorithm

[Programmers] 크레인 인형뽑기

EOZIN 2021. 9. 27. 00:28
728x90

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

import Foundation

var result = 0
func solution(_ board: [[Int]], _ moves:[Int]) -> Int {
    var stack = [Int]()
    var newBoard = board
    for move in moves {
        for i in 0..<board.count {
            if newBoard[i][move - 1] != 0 {
                bomb(&stack, num: newBoard[i][move - 1])
                newBoard[i][move - 1] = 0
                break
            }
        }
    }
    return result
}

func bomb(_ stack: inout [Int], num: Int) {
    if let last = stack.last, last == num {
        stack.removeLast()
        result += 2
        return
    }
    stack.append(num)
}