💡문제접근

  • #으로 둘러싸여 있는 부분에서 양(sheep)의 개체수와 늑대(wolf)의 개체수를 비교하여 만약 양의 개체수가 늑대의 개체수보다 많으면 늑대를 쫒아내고 양의 개체수가 늑대의 개체수보다 적으면 양이 모두 잡아먹히는 것을 표현해주었다.

💡코드(메모리 : 34192KB, 시간 : 220ms)

from collections import deque
import sys
input = sys.stdin.readline

def BFS(a, b):
    sheep = 0
    wolf = 0
    queue = deque()
    queue.append((a, b))
    while queue:
        y, x = queue.popleft()
        dx = [-1, 0, 1, 0]
        dy = [0, 1, 0, -1]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= C or ny < 0 or ny >= R:
                continue
            if 0 <= nx < C and 0 <= ny < R and graph[ny][nx] != '#':
                if graph[ny][nx] == 'o':
                    sheep += 1
                elif graph[ny][nx] == 'v':
                    fox += 1
                graph[ny][nx] = '#'
                queue.append((ny, nx))
    if sheep > wolf:
        return [sheep, 0]
    else:
        return [0, wolf]


R, C = map(int, input().strip().split())
graph = []
result = [0, 0]
for _ in range(R):
    graph.append(list(map(str, input().strip())))

for i in range(R):
    for j in range(C):
        t = BFS(i, j)
        result[0] += t[0]
        result[1] += t[1]
print(*result)

💡소요시간 : 15m

0개의 댓글