728x90
반응형

기본적인 DFS & BFS 문제이다. 3184번 양과 거의 동일한 문제이다. 그냥 BFS으로만 풀었다. 

BFS 풀이

from collections import deque

def bfs(y, x):
    queue = deque()
    queue.append((y, x))
    s = w = 0
    while queue:
        y, x = queue.popleft()
        for dy, dx in d:
            Y, X = y+dy, x+dx
            if (0 <= Y < R) and (0 <= X < C) and graph[Y][X] != '#' and check[Y][X] == 0:
                if graph[Y][X] == 'k':
                    s += 1
                elif graph[Y][X] == 'v':
                    w += 1
                check[Y][X] = 1
                queue.append((Y, X))
    return s, w

R, C = map(int, input().split())
graph = [list(input()) for _ in range(R)]
check = [[0]*(C) for _ in range(R)]
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
S = W = 0
for i in range(R):
    for j in range(C):
        if graph[i][j] != '#' and check[i][j] == 0:
            s = w = 0    
            if graph[i][j] == 'k':
                s += 1
            elif graph[i][j] == 'v':
                w += 1
            check[i][j] = 1
            a, b = bfs(i, j)
            s, w = s+a, w+b
            if s > w:
                w = 0
            else:
                s = 0
            S += s
            W += w
print(S, W)
728x90
반응형

+ Recent posts