Untitled

mail@pastecode.io avatar
unknown
python
5 months ago
2.5 kB
2
Indexable
def B2D(M):
    W = len(M)
    if W == 0:
        return ''
    H = len(M[0])

    def convert(i,j,w,h):
        if w == 0 or h == 0:
            return ''
        count1 = checkAll(M,i,j,w,h)
        if count1 == 0:
            return '0'
        elif count1 == w * h:
            return '1'
        return 'D' + (
            convert(i, j, (w+1)//2, (h+1)//2) +
            convert(i, j+(h+1)//2, (w+1)//2, h//2) +
            convert(i+(w+1)//2, j, w // 2, (h+1)//2) +
            convert(i+(w+1)//2, j+(h+1)//2, w//2, h//2)
        )
    # print(convert(0,0,W,H))
    return convert(0,0,W,H)


def checkAll(M, i, j, w, h):
    count1 = 0
    for ii in range(i, min(i + w, len(M))):
        for jj in range(j, min(j + h, len(M[0]))):
            if M[ii][jj] == '1':
                count1 += 1
    return count1

def inputMatrixB(w, h, str):
    matrix = [[] for _ in range(w)]
    for i, s in enumerate(str):
        matrix[i // h].append(s)
    return matrix


def D2B(stream, W, H):
    if W == 0 or H == 0:
        return ''
    M = [['_' for _ in range(H)] for _ in range(W)]
    string_it = 0

    def convert(i,j,w,h):
        nonlocal M
        nonlocal string_it
        if w == 0 or h == 0:
            return
        c = stream[string_it]
        string_it += 1
        if c != 'D':
            fillAll(M,i,j,w,h,c)
        else:
            convert(i, j, (w+1)//2, (h+1)//2)
            convert(i, j+(h+1)//2, (w+1)//2, h//2)
            convert(i+(w+1)//2, j, w // 2, (h+1)//2)
            convert(i+(w+1)//2, j+(h+1)//2, w//2, h//2)
    
    convert(0, 0, W, H)
    res = []
    for l in M:
        res.append(''.join(l))
    return ''.join(res)

def fillAll(M,i,j,w,h,c):
    for ii in range(i, i+w):
        for jj in range(j, j+h):
            M[ii][jj] = c


def printMatrix(M):
    for l in M:
        print(*l, sep=' ', end='\n')

if __name__ == "__main__":
    while True:
        line = [0,0]
        end = False
        for i in range(2):
            s = input()
            if s == '#':
                end = True
                break
            line[i] = s
        if end:
            break
        symbol, W, H = line[0].split()
        stream = line[1]
        if symbol == 'B':
            M = inputMatrixB(int(W), int(H), stream)
            res = B2D(M)
            print('D', W, H)
            print(res)
        else:
            res = D2B(stream, int(W), int(H))
            print('B', W, H)
            print(res)
Leave a Comment