programming/Algorithm

Softeer: [21년 재직자 대회 예선] 이미지 프로세싱

Roien 2022. 1. 9.
반응형
import sys


H, W = map(int, input().split())
grid = []
for i in range(H):
    grid += list(map(int, input().split())),

Q = int(input())
ops = []
for i in range(Q):
    ops += list(map(int, input().split())),

def fill(grid, clr, nclr, y, x):
    if grid[y][x] != clr or grid[y][x] == nclr:
        return
    
    grid[y][x] = nclr
    
    for oy, ox in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        ny = oy + y
        nx = ox + x
        if not (0 <= ny < H and 0 <= nx < W):
            continue
        
        fill(grid, clr, nclr, ny, nx)

def fillq(grid, clr, nclr, y, x):
    q = [(y, x)]

    while q:
        y, x = q.pop(0)

        if grid[y][x] != clr or grid[y][x] == nclr:
            continue
        
        grid[y][x] = nclr

        for oy, ox in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ny = oy + y
            nx = ox + x
            if not (0 <= ny < H and 0 <= nx < W):
                continue
            
            q += (ny, nx),


for y, x, clr in ops:
    y -= 1
    x -= 1
    fillq(grid, grid[y][x], clr, y, x)


for line in grid:
    print(' '.join([str(val) for val in line]))
반응형

댓글