코딩 테스트/백준
[백준 2638] 치즈
땅어
2022. 4. 16. 14:10
728x90
300x250
문제
https://www.acmicpc.net/problem/2638
2638번: 치즈
첫째 줄에는 모눈종이의 크기를 나타내는 두 개의 정수 N, M (5 ≤ N, M ≤ 100)이 주어진다. 그 다음 N개의 줄에는 모눈종이 위의 격자에 치즈가 있는 부분은 1로 표시되고, 치즈가 없는 부분은 0으로
www.acmicpc.net
나의 풀이
- bfs를 사용하여 풀면 된다.
- 1. bfs를 (0,0)에서부터 시작한다.
- 2. 도중에 공기칸을 만나면 큐에 넣어주고, 치즈칸을 만나면 1을 더해준다.
- 3. 한 번의 bfs를 돌고나서 값이 3 이상인 칸은 2면 이상이 공기와 접하는 것이므로 이 칸의 치즈를 0으로 만든다.
- 4. 1~3을 모든 치즈가 녹을때까지 반복
코드
#https://www.acmicpc.net/problem/2638
import sys
input = sys.stdin.readline
from collections import deque
N, M = map(int, input().split())
arr = []
for _ in range(N):
arr.append(list(map(int, input().strip().split())))
time = 0
def bfs():
q = deque()
q.append((0,0))
visit = set()
visit.add((0,0))
while q:
x, y = q.popleft()
for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
nx, ny = x + dx, y + dy
if 0<=nx<N and 0<=ny<M and (nx,ny) not in visit:
if arr[nx][ny] == 0:
q.append((nx,ny))
visit.add((nx,ny))
else:
arr[nx][ny] += 1
for i in range(N):
for j in range(M):
if arr[i][j] >= 3:
arr[i][j] = 0
elif arr[i][j] == 2:
arr[i][j] = 1
while True:
# terminate condition
total = 0
for i in range(N):
total += sum(arr[i])
if total == 0:
print(time)
break
bfs()
time += 1
728x90
300x250