본문 바로가기
Data Science/알고리즘 공부

[백준][파이썬] 16768 Mooyo Mooyo

by titaniumm 2020. 4. 8.

[핵심]

1. gravity함수 letsdel 함수

n, k = map(int,input().split())
map1 = []
for i in range(n):
    tt = list(input())
    map1.append(tt) #str로 저장한거 기억하기

def gravity(map1): #중력
    temto = []
    temchange = []
    for i in range(10): #열마다
        tem = []
        for j in range(n):#숫자저장
            if map1[j][i] != "0":
                tem.append(map1[j][i])
        for k in range(n-len(tem)): #뒤에 0채워주기
            tem.insert(0,"0")
        temto.append(tem)
    for i in range(n): #행열 바꿔주기
        tem =[]
        for j in range(10):
            tem.append(temto[j][i])
        temchange.append(tem)
    return temchange

dx =[0,0,1,-1]
dy =[1,-1,0,0]
def letsdel(start,stack,count,t,visited):
    global map1
    stack = start
    fordel =[]
    while stack: # 끝까지 다 확인하고 같은 숫자일때 fordel에 저장
        count +=1
        fordel.append(stack[0])
        x = stack[0][0]
        y = stack[0][1]
        visited[x][y] = True
        del stack[0]
        for i in range(4):
            X = x+dx[i]
            Y = y+dy[i]
            if 0<=X<n and 0<=Y <10 and map1[X][Y] == t and visited[X][Y]==False:
                stack.append([X,Y])
                visited[X][Y] = True
    if count >= k:
        for tem in fordel:
            map1[int(tem[0])][int(tem[1])] = "0"
        return map1
    else:
        return map1


map2 = map1
while True:
    map1 = gravity(map1)
    for i in range(n):
        for j in range(10):
            if map1[i][j] !=0:
                visited = [[False for _ in range(10)] for __ in range(n)]
                t = map1[i][j]
                letsdel([[i,j]],[],0,t,visited)
    if map1 == map2:
        break
    else:
        map2 = map1

for i in range(n):
    print("".join(map1[i]))

댓글