Baekjoon 7576

BFS

Baekjoon 7576

Description

철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다. 창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.

토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.

Input

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.

토마토가 하나 이상 있는 경우만 입력으로 주어진다.

Output

여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.

Example I & O

Input
6 4
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 1

Output
8

Input
6 4
0 -1 0 0 0 0
-1 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 1

Output
-1

Input
6 4
1 -1 0 0 0 0
0 -1 0 0 0 0
0 0 0 0 -1 0
0 0 0 0 -1 1

Output
6

Input
5 5
-1 1 0 0 0
0 -1 -1 -1 0
0 -1 -1 -1 0
0 -1 -1 -1 0
0 0 0 0 0

Output
14

Input
2 2
1 -1
-1 1

Output
0

My solution

import sys
from collections import deque

input = sys.stdin.readline
print = sys.stdout.write

M, N = map(int, input().split())
farm = []
dayGraph = [[-1 for i in range(M)] for i in range(N)]
start_tomatoes = []

for i in range(N):
    row = input().split()
    for j in range(M):
        if row[j] == "-1" or row[j] == "1":
            dayGraph[i][j] = 0
            if row[j] == "1":
                start_tomatoes.append((j, i))
    farm.append(row)

def BFS(graph, distance, start):
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]
    need_v = deque(start)

    while need_v:
        x, y = need_v.popleft()
        for i in range(4):
            next_x = x + dx[i]
            next_y = y + dy[i]
            if next_x < 0 or next_x >= M or next_y < 0 or next_y >= N:
                continue
            elif graph[next_y][next_x] == "-1" or graph[next_y][next_x] == "1":
                continue
            elif distance[next_y][next_x] != -1:
                continue
            else:
                need_v.append((next_x, next_y))
                distance[next_y][next_x] = distance[y][x] + 1


BFS(farm, dayGraph, start_tomatoes)

maximum = 0

for i in range(N):
    if -1 in dayGraph[i]:
        maximum = -1
        break
    if maximum < max(dayGraph[i]):
        maximum = max(dayGraph[i])

print(str(maximum))
  • Sketch

Use input as the graph directly (not using adjacent list)

Shortest Distance resulted from BFS == Minimum days needed for a tomato located on (x, y) ripening

Multi-starting points for BFS : There are some tomatoes which already ripened → If at first we put these tomatoes’ location into deque (BFS) at the same time, we can calculate final minimum days for all of locations

  • Code Analysis
M, N = map(int, input().split())
farm = []
dayGraph = [[-1 for i in range(M)] for i in range(N)]
start_tomatoes = []

for i in range(N):
    row = input().split()
    for j in range(M):
        if row[j] == "-1" or row[j] == "1":
            dayGraph[i][j] = 0
            if row[j] == "1":
                start_tomatoes.append((j, i))
    farm.append(row)

farm : the input graph
dayGraph : the minimum days for each (x, y)
start_tomatoes : multi-starting points
Starting point & no tamoto location : dayGraph = 0 → If there are some tomatoes which weren’t searched by BFS, its value of dayGraph is -1


def BFS(graph, distance, start):
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]
    need_v = deque(start)

    while need_v:
        x, y = need_v.popleft()
        for i in range(4):
            next_x = x + dx[i]
            next_y = y + dy[i]
            if next_x < 0 or next_x >= M or next_y < 0 or next_y >= N:
                continue
            elif graph[next_y][next_x] == "-1" or graph[next_y][next_x] == "1":
                continue
            elif distance[next_y][next_x] != -1:
                continue
            else:
                need_v.append((next_x, next_y))
                distance[next_y][next_x] = distance[y][x] + 1

need_v = deque(start) : Multi-starting points
normal BFS
We don’t need to use visited of BFS if we use distance list for tracking the nodes


BFS(farm, dayGraph, start_tomatoes)

maximum = 0

for i in range(N):
    if -1 in dayGraph[i]:
        maximum = -1
        break
    if maximum < max(dayGraph[i]):
        maximum = max(dayGraph[i])

print(str(maximum))

We need the minimum days of the last ripened tomato : Maximum value from dayGraph


Time Complexity

  • We don’t need to use visited of BFS if we use distance list for tracking the nodes
    • If we use extra list (visited) despite using distance list, it is more inefficient
      • Making extra list + append operation : it is more inefficient than we expected
    • reference (important) : Saving Time Complexity

© 2017. All rights reserved.

Powered by Hydejack v조현진