boj 7576

less than 1 minute read

“https://www.acmicpc.net/problem/7576”

import sys
from collections import deque 
col, row = map(int, sys.stdin.readline().split())
box = [list(map(int, sys.stdin.readline().split())) for _ in range(row)]

dx, dy = [-1,1,0,0], [0,0,1,-1]
start_list = deque() ## start하는 좌표들
days = 0
for c in range(row):
    for r in range(col):
        if box[c][r] == 1:
            start_list.append((c,r))
            
def bfs(box, start_list, days):
    while True:
        start_temp = deque()
        while start_list:
            x, y = start_list.popleft()
            for j in range(4):
                nx, ny = x + dx[j], y + dy[j]
                if 0<=nx<row and 0<=ny<col and (box[nx][ny] == 0):
                    start_temp.append((nx,ny))
                    box[nx][ny] = 1  
        start_list = start_temp ## 이렇게 하는 것이 이중 for 사용하지 않고 더 빠르게 해결할 수 있다. --> 이 부분이 days 를 1 추가할 수 있도록 해주는 세팅
        if not start_list:
            break
        days += 1      
    for b in box:
        if 0 in b:
            return -1
    return days

if __name__ == "__main__":
    print(bfs(box, start_list, days))          
notion
  • python에서 시간초과가 날때!!
  • deque와 popleft를 활용해라

Categories:

Updated: