본문 바로가기
문제 해결/BOJ

[백준] 치즈

by 자잘 2023. 3. 23.

https://www.acmicpc.net/problem/2638

 

2638번: 치즈

첫째 줄에는 모눈종이의 크기를 나타내는 두 개의 정수 N, M (5 ≤ N, M ≤ 100)이 주어진다. 그 다음 N개의 줄에는 모눈종이 위의 격자에 치즈가 있는 부분은 1로 표시되고, 치즈가 없는 부분은 0으로

www.acmicpc.net

BFS를 활용한 문제입니다. 가장자리(0,0)부터 BFS를 통해 사방탐색을 진행하면서 다음이 빈 공간이면 큐에 넣어주고 치즈이면 공기와 맞닿아있는 치즈이므로 cnt를 늘려준 다음 2이상인 치즈는 제거해주면 됩니다.

 

import sys
from collections import deque
sys.stdin = open("input.txt", "r")
input = sys.stdin.readline


n, m = tuple(map(int, input().split()))

board = [
    list(map(int, input().split()))
    for _ in range(n)
]


dys = [0, 1, 0, -1]
dxs = [1, 0, -1, 0]

t = 0

def inRange(y, x):
    return 0 <= y < n and 0 <= x < m


def bfs():
    visited = [
        [False] * m
        for _ in range(n)
    ]

    cnt = [
        [0] * m
        for _ in range(n)
    ]

    visited[0][0] = True

    q = deque([(0, 0)])

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

        for dy, dx in zip(dys, dxs):
            ny = y + dy
            nx = x + dx
            if inRange(ny, nx) and not visited[ny][nx]:
                # 다음이 치즈이면 실내 공기와 접촉했으므로 1증가
                if board[ny][nx] == 1:
                    cnt[ny][nx] += 1
                else:
                    visited[ny][nx] = True
                    q.append((ny, nx))

    isExist = 0
    for i in range(n):
        for j in range(m):
            if board[i][j]:
                isExist += 1

            if cnt[i][j] >= 2:
                board[i][j] = 0

    return False if isExist == 0 else True




while bfs():
    t += 1

print(t)

'문제 해결 > BOJ' 카테고리의 다른 글

[백준] 벡터 매칭  (0) 2023.03.25
[백준] 양팔저울  (0) 2023.03.24
[백준] 백양로 브레이크  (0) 2023.03.22
[백준] 학교 탐방하기  (0) 2023.03.21
[백준] 동방 프로젝트(large)  (0) 2023.03.20