https://www.acmicpc.net/problem/3187
3187번: 양치기 꿍
입력의 첫 번째 줄에는 각각 영역의 세로와 가로의 길이를 나타내는 두 개의 정수 R, C (3 ≤ R, C ≤ 250)가 주어진다. 다음 각 R줄에는 C개의 문자가 주어지며 이들은 위에서 설명한 기호들이다.
www.acmicpc.net
from collections import deque
r, c = map(int, input().split())
a = [list(input()) for _ in range(r)]
check = [[False] * c for _ in range(r)]
# 빈 . , 울 # , 늑 v, 양 k
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
def bfs(n1, n2):
global wolf, sheep
check[n1][n2] = True
queue = deque()
queue.append((n1, n2))
while queue:
x, y = queue.popleft()
if a[x][y] == 'v':
wolf += 1
elif a[x][y] == 'k':
sheep += 1
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < r and 0 <= ny < c and check[nx][ny] == False:
if a[nx][ny] != '#':
queue.append((nx, ny))
check[nx][ny] = True
ans = [0, 0] # 양, 늑대
for i in range(r):
for j in range(c):
if a[i][j] != '#' and check[i][j] == False:
sheep, wolf = 0, 0
bfs(i, j)
if sheep > wolf:
ans[0] += sheep
if wolf >= sheep:
ans[1] += wolf
print(*ans)
그래프를 bfs로 전체 탐색한 뒤
울타리로 둘러져 있는 곳을 한 구역으로 지정,
해당 구역의 양과 늑대의 총 수를 구한 뒤 비교하여 제출해주면 됨.
'백준 알고리즘 (Baekjoon Algorithm)' 카테고리의 다른 글
[파이썬] 백준 알고리즘 No.16948 데스 나이트 (0) | 2022.01.26 |
---|---|
[파이썬] 백준 알고리즘 No.16928 뱀과 사다리 게임 (0) | 2022.01.26 |
[파이썬] 백준 알고리즘 No.9663 N-Queen (0) | 2022.01.24 |
[파이썬] 백준 알고리즘 No.16198 에너지 모으기 (0) | 2022.01.23 |
[파이썬] 백준 알고리즘 No.16197 두 동전 (0) | 2022.01.23 |