728x90
반응형

기본적인 DFS & BFS 문제이다.

DFS 풀이

import sys
sys.setrecursionlimit(3000000)

def dfs(y, x, K, n):
    graph[y][x] = K
    for dy, dx in d:
        Y, X = y+dy, x+dx
        if (0 <= Y < R) and (0 <= X < C) and graph[Y][X] == n:
            dfs(Y, X, K, n)
            
R, C = map(int, input().split())
graph = [list(input()) for _ in range(R)]
Y, X, K = map(int, input().split())
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
dfs(Y, X, str(K), graph[Y][X])
for line in graph:
    print(''.join(line))

BFS 풀이

from collections import deque

def bfs(y, x, K):
    q = deque()
    q.append((y, x))
    n = graph[y][x]
    graph[y][x] = K
    while q:
        y, x = q.popleft()
        for dy, dx in d:
            Y, X = y+dy, x+dx
            if (0 <= Y < R) and (0 <= X < C) and graph[Y][X] == n:
                q.append((Y, X))
                graph[Y][X] = K

R, C = map(int, input().split())
graph = [list(input()) for _ in range(R)]
Y, X, K = map(int, input().split())
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
bfs(Y, X, str(K))
for line in graph:
    print(''.join(line))
728x90
반응형

+ Recent posts