Algorithm (PS)
                
              [백준] 3184번: 양 Python - BFS풀이
                minjiwoo
                 2023. 1. 10. 20:14
              
              
                    
        728x90
    
    
  https://www.acmicpc.net/problem/3184
3184번: 양
첫 줄에는 두 정수 R과 C가 주어지며(3 ≤ R, C ≤ 250), 각 수는 마당의 행과 열의 수를 의미한다. 다음 R개의 줄은 C개의 글자를 가진다. 이들은 마당의 구조(울타리, 양, 늑대의 위치)를 의미한다.
www.acmicpc.net
전형적인 dfs/bfs 문제라고 생각함
나는 bfs로 풀었다
from collections import deque
r, c = map(int, input().split())
array = []
sheep = 0
wolf = 0
for i in range(r):
    array.append(input())
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
visited = [[False] * c for _ in range(r)]
def bfs(a, b):
    global visited
    temp_sheep = 0
    temp_wolf = 0
    queue = deque([])
    queue.append((a, b))
    visited[a][b] = True
    if array[a][b] == 'o':
        temp_sheep += 1
    if array[a][b] == 'v':
        temp_wolf += 1
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < r and 0 <= ny < c and not visited[nx][ny] and array[nx][ny] != '#':
                if array[nx][ny] == 'o':
                    temp_sheep += 1
                    visited[nx][ny] = True
                    queue.append((nx, ny))
                if array[nx][ny] == 'v':
                    temp_wolf += 1
                    visited[nx][ny] = True
                    queue.append((nx, ny))
                if array[nx][ny] == '.': # .
                    visited[nx][ny] = True
                    queue.append((nx, ny))
    if temp_sheep > temp_wolf:
        return temp_sheep, 0
    else:
        return 0, temp_wolf
for i in range(r):
    for j in range(c):
        if array[i][j] != '#' and visited[i][j] == False:
                result = bfs(i, j)
                sheep += result[0]
                wolf += result[1]
print(sheep, wolf)728x90