본문 바로가기
알고리즘

[Swift] 프로그래머스 - 카카오 크레인 인형뽑기 게임

by 고고 2022. 2. 10.

문제: 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

func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
    var board = board
    var queue = [Int]()
    var result = 0
    
    func addDoll(doll: Int) {
        if queue.last == doll {
            result += 2
            queue.removeLast()
        } else {
            queue.append(doll)
        }
    }
    
    for move in moves {
        for i in 0..<board.count {
            if board[i][move - 1] == 0 { continue }
            
//            print(move, board[i][move - 1])
            
            addDoll(doll: board[i][move - 1])
            board[i][move - 1] = 0
            break
        }
    }
    
    return result
}

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

댓글