(Python) 프로그래머스 - 기둥과 보 설치

[문제 링크]

풀이

def solution(n, build_frame):
    result = []
    
    for x, y, a, b in build_frame:
        # 설치
        if b == 1:
            if can_build(x, y, a, result):
                result.append([x, y, a])

        # 삭제
        else:
            result.remove([x, y, a])
            for px, py, pa in result:
                if not can_build(px, py, pa, result):
                    result.append([x, y, a])
                    break

    result.sort()
    return result


def can_build(x, y, a, result):
    # 기둥
    if a == 0:
        # 바닥에 설치하거나 바닥에 보나 기둥이 있는 경우 설치 가능
        if y == 0 or [x, y - 1, 0] in result or [x - 1, y, 1] in result or [x, y, 1] in result:
            return True
    # 보
    else:
        # 양끝에 보가 있거나 한쪽 끝에 기둥이 있으면 설치 가능
        if ([x - 1, y, 1] in result and [x + 1, y, 1] in result) or [x, y - 1, 0] in result or [x + 1, y - 1, 0] in result:
            return True

    return False


print(solution(5, [[0, 0, 0, 1], [2, 0, 0, 1], [4, 0, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1], [2, 1, 1, 1], [3, 1, 1, 1],
                   [2, 0, 0, 0], [1, 1, 1, 0], [2, 2, 0, 1]]))

© 2021. By Backtony