λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 3184 - μ–‘

by HandHand 2021. 3. 18.

문제

λ°±μ€€ 온라인 저지 - 3184번

풀이 κ³Όμ •

BFS 탐색을 톡해 λͺ¨λ“  μ˜μ—­μ„ 탐색해쀀 λ’€ λŠ‘λŒ€μ˜ μˆ˜μ™€ μ–‘μ˜ 수λ₯Ό νŒŒμ•…ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
μ €λŠ” λŠ‘λŒ€μ˜ μœ„μΉ˜μ—μ„œλΆ€ν„° BFS 탐색을 μˆ˜ν–‰ν–ˆμ§€λ§Œ
κ·Έλƒ₯ 아직 λ°©λ¬Έν•˜μ§€ μ•Šμ€ λΉˆμΉΈμ—μ„œλΆ€ν„° BFS 탐색을 μ‹œμž‘ν•΄λ„ 상관없을 것 κ°™μŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys
from collections import deque


R, C = list(map(int, sys.stdin.readline().split()))
board = []
wolves = []
sheep = []
for r in range(R):
    line = list(sys.stdin.readline()[:-1])
    board.append(line)

    for c in range(C):
        if line[c] == 'v':
            wolves.append([r, c])
        if line[c] == 'o':
            sheep.append([r, c])


visit = [[False] * C for _ in range(R)]
dx = [0 ,0, 1, -1]
dy = [1, -1, 0, 0]


def bfs(start):
    w_c = 1
    s_c = 0

    q = deque()
    q.append([start[0], start[1]])
    visit[start[0]][start[1]] = True

    while q:
        x, y = q.popleft()

        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]

            if 0 <= next_x < R and 0 <= next_y < C:
                if board[next_x][next_y] != '#' and not visit[next_x][next_y]:
                    visit[next_x][next_y] = True
                    q.append([next_x, next_y])
                    if board[next_x][next_y] == 'v':
                        w_c += 1
                    if board[next_x][next_y] == 'o':
                        s_c += 1

    return w_c, s_c


def solution():
    init_wolf = len(wolves)
    init_sheep = len(sheep)
    for wolf in wolves:
        if not visit[wolf[0]][wolf[1]]:
            w_c, s_c = bfs(wolf)
            if w_c < s_c:
                init_wolf -= w_c
            else:
                init_sheep -= s_c

    print(init_sheep, init_wolf)


solution()
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€