N × M 크기의 얼음 틀이 있다. 구멍이 뚫려 있는 부분은 0, 칸막이가 존재하는 부분은 1로 표시된다.
구멍이 뚫려 있는 부분끼리 상, 하, 좌, 우로 붙어 있는 경우 서로 연결되어 있는 것으로 간주한다.
이때 얼음 틀의 모양이 주어졌을 때 생성되는 총 아이스크림의 개수를 구하는 프로그램을 작성하라.
다음의 4 × 5 얼음 틀 예시에서는 아이스크림이 총 3개가 생성된다
첫 번째 줄에 얼음 틀의 세로 길이 N과 가로 길이 M이 주어진다. (1 <= N, M <= 1,000)
두 번째 줄부터 N + 1 번째 줄까지 얼음 틀의 형태가 주어진다.
이때 구멍이 뚫려있는 부분은 0, 그렇지 않은 부분은 1이다.
한 번에 만들 수 있는 아이스크림의 개수를 출력한다.
4 5
00110
00011
11111
00000
3
from collections import deque
def input_data():
N, M = map(int, input().split())
icemaker = list()
for i in range(N):
icemaker.append([])
temp = str(input())
icemaker[i] = [int(i) for i in temp]
return icemaker
def bfs(N, M, icemaker):
icemaker[N][M] = 1
queue = deque([[N, M]])
while queue:
current = queue.popleft()
for i in [[-1, 0], [0, -1], [1, 0], [0, 1]]:
if current[0] + i[0] >= 0 and current[0] + i[0] < len(icemaker) and current[1] + i[1] >= 0 and current[1] + i[1] < len(icemaker[0]):
if icemaker[current[0] + i[0]][current[1] + i[1]] == 0:
icemaker[current[0] + i[0]][current[1] + i[1]] = 1
queue.append([current[0] + i[0], current[1] + i[1]])
return icemaker
def exe():
count = 0
icemaker = input_data()
for i in range(len(icemaker)):
for k in range(len(icemaker[0])):
if icemaker[i][k] == 0:
count += 1
icemaker = bfs(i, k, icemaker)
print(count)
exe()
BFS 방식으로 풀어보았다!