Algorithm/programmers

프렌즈4블록 ( Level 2, JavaScript, 2018 KAKAO BLIND RECRUITMENT)

takeU 2025. 1. 12. 14:57
반응형
const checkSquare = (board, x, y) => {
    const block = board[x][y]
    if (board[x + 1][y] === block
        && board[x][y + 1] === block
        && board[x + 1][y + 1] === block) return true
    return false
}

const checkTargetBlocks = (m, n, board) => {
    const targetBlocks = []
    for (let i = 0; i < m - 1; i++) {
        for (let j = 0; j < n - 1; j++) {
            if (board[i][j] !== 'X' && checkSquare(board, i, j)) targetBlocks.push([i, j])
        }
    }
    return targetBlocks
}

const removeBlocks = (m, n, board, targetBlocks) => {
    let count = 0
    targetBlocks.forEach(([x, y]) => {
        board[x][y] = 'Xcur'
        board[x + 1][y] = 'Xcur'
        board[x][y + 1] = 'Xcur'
        board[x + 1][y + 1] = 'Xcur'
    })

    for (let j = 0; j < n; j++) {
        let col = ''
        for (let i = m - 1; i >= 0; i--) {
            col += board[i][j]
        }
        col = col.replace(/Xcur/g, '')
        count += m - col.length
        col += 'X'.repeat(m - col.length)
        for (let i = m - 1; i >= 0; i--) {
            board[i][j] = col[(m - 1) - i]
        }
    }
    return count
}

const solution = (m, n, board) => {
    let res = 0
    board = board.map(board => board.split(''))
    while (true) {    
        const targetBlocks = checkTargetBlocks(m, n, board)
        if (targetBlocks.length === 0) return res
        res += removeBlocks(m, n, board, targetBlocks)
    }
}

그냥 나와있는대로 구현만 잘 하면댐