Jae-Kyung Cho LLM Developers who was a Robotics engineer

Baekjoon-2933-미네랄

from audioop import reverse
import sys
input = sys.stdin.readline

R,C = map(int, input().split())
cave = []
for _ in range(R):
    line = [c for c in input().strip()]
    cave.append(line)
cave.reverse() # upside down

N = int(input())
heights = list(map(int,input().split()))

dirs = [(0,1),(0,-1),(1,0),(-1,0)]

for turn,h in enumerate(heights):
    # throw rod
    if turn % 2 == 0: # left to right
        for i in range(C):
            if cave[h-1][i] == 'x':
                cave[h-1][i] = '.'
                break
    else:
        for i in reversed(range(C)):
            if cave[h-1][i] == 'x':
                cave[h-1][i] = '.'
                break

    # Find float cluster (BFS from h,i)
    isground = -1
    candidates = [(h,i),(h-2,i)]
    if turn % 2 == 0:
        candidates += [(h-1,i+1)]
    else:
        candidates += [(h-1,i-1)]

    for cand_i,cand_j in candidates:
        if isground == 0:
            break
        if 0<=cand_i<R and 0<=cand_j<C and cave[cand_i][cand_j] == 'x':
            isground = -1
            visited = [[0]*C for _ in range(R)]
            visited_w = [cand_j]
            q = [(cand_i, cand_j)]
            visited[cand_i][cand_j] = 1
            while q:
                x,y = q.pop(0)
                for dx,dy in dirs:
                    if 0<=x+dx<R and 0<=y+dy<C:
                        if visited[x+dx][y+dy]==0 and cave[x+dx][y+dy]=='x':
                            q.append((x+dx,y+dy))
                            if not y+dy in visited_w:
                                visited_w.append(y+dy)
                            visited[x+dx][y+dy] = 1
                            if x+dx==0:
                                isground = 1
                if isground == 1:
                    break
            if isground == -1:
                isground = 0

    # gravity
    if isground == 0:
        # find drop height
        min_h = R
        for j in visited_w:
            for i in range(R):
                if visited[i][j] == 1:
                    break
            min_h = min(min_h, i+1)
            for k in reversed(range(i)):
                if cave[k][j] == 'x':
                    min_h = min(min_h, i-k)
                    break
            
        for j in visited_w:
            for i in range(R):
                if visited[i][j] == 1:
                    cave[i-min_h+1][j] = 'x'
                    cave[i][j] = '.'


cave.reverse()
for line in cave:
    print(*line,sep='')
Comments