2020 KAKAO BLIND RECRUITMENT - 기둥과 보 설치 (Level 3)

 

https://programmers.co.kr/learn/courses/30/lessons/60061


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def solution(n, build_frame):
    def check_valid_pol(x, y, pols, floors):
        return any([
            y == 0,
            (x - 1, y) in floors,
            (x, y) in floors,
            (x, y - 1) in pols
        ])
    def check_valid_floor(x, y, pols, floors):
        return any([
            (x, y - 1) in pols,
            (x + 1, y - 1) in pols,
            ((x - 1, y) in floors) and ((x + 1, y) in floors)
        ])
    def check_add(x, y, a, pols, floors):
        if a == 0:  # 기둥
            return check_valid_pol(x, y, pols, floors)
        else:  # 보
            return check_valid_floor(x, y, pols, floors)
    def check_rm(x, y, a, pols, floors):
        if a == 0: # 기둥
            rm_pols = pols - {(x, y)}
            cond1 = check_valid_floor(x-1, y, rm_pols, floors) if (x-1, y) in floors else True
            cond2 = check_valid_floor(x, y, rm_pols, floors) if (x, y) in floors else True
            cond3 = check_valid_floor(x-1, y+1, rm_pols, floors) if (x-1, y+1) in floors else True
            cond4 = check_valid_floor(x, y+1, rm_pols, floors) if (x, y+1) in floors else True
            cond5 = check_valid_pol(x, y+1, rm_pols, floors) if (x, y+1) in pols else True
            return all([cond1, cond2, cond3, cond4, cond5])
        else:  # 보
            rm_floors = floors - {(x, y)}
            cond1 = check_valid_floor(x-1, y, pols, rm_floors) if (x-1, y) in floors else True
            cond2 = check_valid_floor(x+1, y, pols, rm_floors) if (x+1, y) in floors else True
            cond3 = check_valid_pol(x, y, pols, rm_floors) if (x, y) in pols else True
            cond4 = check_valid_pol(x+1, y, pols, rm_floors) if (x+1, y) in pols else True
            return all([cond1, cond2, cond3, cond4])


    pols   = set()
    floors = set()

    for x, y, a, b in build_frame:
        if b == 0: # 삭제
            if check_rm(x, y, a, pols, floors):
                if a == 0:  # 기둥
                    pols -= {(x, y)}
                else:
                    floors -= {(x, y)}
        else:  # 설치
            if check_add(x, y, a, pols, floors):
                if a == 0:  # 기둥
                    pols |= {(x, y)}
                else:  # 보
                    floors |= {(x, y)}

        # print("x, y, a, b:" , x, y, a, b)
        # print("pols:", pols)
        # print("floors:", floors)
        # print("=====================")

    rst = [[x, y, 0] for x, y in pols] + [[x, y, 1] for x, y in floors]
    return sorted(rst)

Complexity

$O(n)$
$n: len(build_frame)$