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

 

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


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
from itertools import product

def solution(m, n, board):
    # 1. Convert to 2d-array
    board = [list(row) for row in board]


    # 2. Prepare functions
    get_idxs_box  = lambda r, c: [(r+s_r, c+s_c) for s_r, s_c in product([0, 1], [0, 1])]
    get_box       = lambda idxs: [board[r][c] for r, c in idxs]
    get_board_removed = lambda: [n*[False] for _ in range(m)]


    # 3. Search
    n_removed = 0
    while True:
        term_cond = True

        ## 3.1 Remove blocks
        board_removed = get_board_removed()
        for r, c in product(range(m-1), range(n-1)):
            idxs_box = get_idxs_box(r, c)
            box = set(get_box(idxs_box))
            if box != {None} and len(box) == 1:
                for r, c in idxs_box:
                    if not board_removed[r][c]:
                        board_removed[r][c] = True
                        n_removed += 1
                        term_cond = False

        ## 3.2 Update board
        board = [[None if board_removed[r][c] else board[r][c] for c in range(n)] for r in range(m)]

        ## 3.3 Fall blocks
        cols = []
        for c in range(n):
            col = [board[r][c] for r in reversed(range(m)) if board[r][c] is not None]  # 아래에서 위로
            col = [col[r] if len(col) > r else None for r in range(m)][::-1]  # 위에서 아래로
            cols.append(col)
        for r, c in product(range(m), range(n)):
            board[r][c] = cols[c][r]

        if term_cond:
            break
    return n_removed

Complexity

$O(mn)$