백준 3184번 양

highway92·2021년 10월 4일
0

백준

목록 보기
15/27

문제출처 : https://www.acmicpc.net/problem/3184

풀이과정

  1. 울타리, 양, 늑대를 표시한 table과
    방문여부를 알려주는 check테이블을 만든다.
  2. for문을 돌면서 o,v를 발견하면 영역 내 모두를 돌아다니며 o,v를 체크하여 animals 리스트에 넣는다. (돌아다니며 check리스트 값 바꿔준다.)
  3. animals 데이터의 각 리스트는 같은 영역내의 양과 늑대 수이므로 답을 산출해낼 수 있다.

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

y,x = map(int,input().split())

table = [list(input()[:-1]) for i in range(y)]
check = [[False]*x for i in range(y)]
dx=[1,-1,0,0]
dy=[0,0,1,-1]
answer =[0,0]

animals =[] #[양 수(o), 늑대 수(v)] 가 들어갈 리스트

for _y in range(y):
    for _x in range(x):
        result = [0,0]
        q = deque()
        if table[_y][_x] == "o" and check[_y][_x] == False:
            check[_y][_x] = True
            result[0] += 1
            q.append([_y,_x])
        elif table[_y][_x] == "v" and check[_y][_x] == False:
            check[_y][_x] = True
            result[1] += 1
            q.append([_y,_x])

        while q:
            location = q.popleft()
            for i in range(4):
                b = location[0] + dy[i] if 0<= location[0] + dy[i] < y else location[0]
                a = location[1] + dx[i] if 0 <= location[1] + dx[i] < x else location[1]
                if table[b][a] == "o" and check[b][a] == False:
                    check[b][a] = True
                    result[0] += 1
                    q.append([b,a])
                elif table[b][a] == "v" and check[b][a] == False:
                    check[b][a] = True
                    result[1] += 1
                    q.append([b,a])
                elif table[b][a] == "." and check[b][a] == False:
                    check[b][a] = True
                    q.append([b,a])

        if sum(result) > 0:
            animals.append(result)

for i in animals:
    if i[0] > i[1]:
        answer[0] += i[0]
    else:
        answer[1] += i[1]

print(*answer)
profile
웹 개발자로 활동하고 있습니다.

0개의 댓글