공부하고 기록하는, 경제학과 출신 개발자의 노트

프로그래밍/코딩테스트 문제풀이

[Python] 구름. 달걀 부화기

inspirit941 2020. 3. 18. 20:35
반응형

https://level.goorm.io/exam/43144/%EB%8B%AC%EA%B1%80-%EB%B6%80%ED%99%94%EA%B8%B0/quiz/1

 

구름LEVEL

난이도별 다양한 문제를 해결함으로써 SW 역량을 향상시킬 수 있습니다.

level.goorm.io

 

출력 부문의 설명이 별로 명확하지 않다.

 

'처음부터 달걀이 전부 부화한 상태일 경우' 0 출력

'처음부터 달걀이 부화할 수 없는 상태일 경우' -1 출력

이외의 경우, 부화할 때까지의 최소 날짜를 출력하라는 뜻이다.

 

 

 

# -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
from collections import deque
M, N = map(int, input().split())
maps = []
start = []
for y in range(N):
temp = list(map(int, input().split()))
for x in range(M):
if temp[x] == 1:
start.append((y, x, 0))
maps.append(temp)
def bfs(start, maps):
queue = deque()
queue.extend(start)
dirs = [(0,1),(0,-1),(1,0),(-1,0)]
# 처음부터 '부화한 달걀' 이 없을 경우 == -1 반환
if not queue:
return -1
while queue:
y, x, cnt = queue.popleft()
for dy, dx in dirs:
ny, nx = y + dy, x + dx
if 0 <= ny < len(maps) and 0 <= nx < len(maps[0]):
if maps[ny][nx] == 0:
maps[ny][nx] = 1
queue.append((ny, nx, cnt+1))
return cnt
def is_zero(maps):
for y in range(N):
if maps[y].count(0) != 0:
return True
return False
answer = bfs(start, maps)
# 달걀이 부화하지 못한 게 하나라도 남아 있을 경우
if is_zero(maps):
print(-1)
else:
print(answer)
반응형