Skip to content

Commit 4191ade

Browse files
committed
[22.02.22] 2636 - 너비우선탐색
1 parent 3dab910 commit 4191ade

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Python_BOJ_2022/2636.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# 치즈
2+
from collections import deque
3+
4+
n, m = map(int, input().split())
5+
graph = [list(map(int, input().split())) for _ in range(n)]
6+
7+
# 전체 치즈 갯수가 몇갠지 맨 처음 카운트
8+
left_cheese = 0
9+
for i in range(n):
10+
for j in range(m):
11+
if graph[i][j] == 1:
12+
left_cheese += 1
13+
14+
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
15+
16+
# 치즈 테두리를 너비우선탐색으로 돌며 2로 바꿔준다
17+
def bfs(cheese):
18+
queue = deque()
19+
queue.append((0, 0))
20+
visited[0][0] = True
21+
while queue:
22+
x, y = queue.popleft()
23+
for i in range(4):
24+
nx, ny = x + dx[i], y + dy[i]
25+
if 0 <= nx < n and 0 <= ny < m:
26+
if not visited[nx][ny]:
27+
visited[nx][ny] = True
28+
if graph[nx][ny] == 1:
29+
graph[nx][ny] = 2
30+
cheese -= 1
31+
# print_graph()
32+
else:
33+
queue.append((nx, ny))
34+
return cheese
35+
36+
cnt = 0
37+
tmp = left_cheese
38+
39+
# def print_graph():
40+
# print('===================================================')
41+
# for i in range(n):
42+
# for j in range(m):
43+
# print(graph[i][j], end=' ')
44+
# print()
45+
46+
# 테두리 부분 치즈를 없앤다.
47+
def remove_cheese():
48+
for i in range(n):
49+
for j in range(m):
50+
if graph[i][j] == 2:
51+
graph[i][j] = 0
52+
53+
# 치즈의 갯수가 존재하는 동안 계속 탐색
54+
while left_cheese:
55+
visited = [[False] * m for _ in range(n)]
56+
left_cheese = bfs(left_cheese)
57+
if left_cheese != 0:
58+
tmp = left_cheese
59+
cnt += 1
60+
remove_cheese()
61+
62+
print(cnt)
63+
print(tmp)

0 commit comments

Comments
 (0)