백준 3184번 양

Solution

import sys

input = sys.stdin.readline
sys.setrecursionlimit(100000)

move = [[1, 0], [0, 1], [-1, 0], [0, -1]]


def dfs(x, y):
    global s, w
    visit[x][y] = True
    if graph[x][y] == 'o':
        s += 1
    elif graph[x][y] == 'v':
        w += 1
    for dx, dy in move:
        nx = x + dx
        ny = y + dy
        if 0 <= nx < r and 0 <= ny < c and graph[nx][ny] != '#' and not visit[nx][ny]:
            dfs(nx, ny)


r, c = map(int, input().split())
graph = [list(input().strip()) for i in range(r)]

visit = [[False] * c for _ in range(r)]

sheep = 0
wolf = 0
for i in range(r):
    for j in range(c):
        s = 0
        w = 0
        if graph[i][j] != '#' and not visit[i][j]:
            dfs(i, j)
            if s > w:
                sheep += s
            else:
                wolf += w
print(sheep, wolf)