minyeamer
Minystory
minyeamer
edit settings
전체 방문자
오늘
어제
  • Category List (104)
    • Books (5)
      • Book Reviews (1)
      • Paper Reviews (4)
    • Life (4)
      • Blog (3)
      • Item Reviews (0)
      • Thoughts (1)
    • Study (37)
      • 2022 (3)
      • AI SCHOOL (34)
      • References (0)
    • Tech (58)
      • Algorithm (47)
      • Projects (9)
      • Python (2)

Blog Menu

  • Home
  • Notice
  • Tags
  • Guest

Popular Posts

Recent Comments

Recent Posts

hELLO
minyeamer

Minystory

Tech/Algorithm

[백준 7576] 토마토 (Python)

2022. 8. 24. 10:38

문제 링크

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

문제 해설

Idea

  • BFS를 활용한 시뮬레이션을 통해 모든 토마토가 익을 떄까지 걸리는 최소 기간을 계산
  • 초기엔 안익은 토마토의 기준에서 매번 익은 토마토까지의 최단거리를 탐색하여,
    O(N^4)의 시간 복잡도로 시간 초과가 발생
  • 이후 익은 토마토의 기준에서 시뮬레이션을 단 한번만 수행하여 각각의 칸에 도달하는데 걸리는 거리값을 갱신
  • 모두 익지 못하는 상황에 대해 1안에선 에러를 발생시켜 처리했고, 2안에선 종료 코드를 실행해 처리

Time Complexity

  • O(N^2) = 1,000,000

Data Size

  • M,N: 2 <= int <= 1,000
  • t in [1,0,-1]

해설 코드

from collections import deque
import sys
input = sys.stdin.readline

M, N = map(int, input().split())
box = [list(map(int, input().split())) for _ in range(N)]
days = 0

# ============== 1안 (시간초과) =============

def bfs(graph, start, n, m, vistied):
    queue = deque([start])
    dist = 0

    dy = [0,1,0,-1]
    dx = [-1,0,1,0]

    while queue:
        for _ in range(len(queue)):
            y,x = queue.popleft()
            if graph[y][x] == 1:
                return dist
            for i in range(4):
                ny,nx = y+dy[i],x+dx[i]
                if 0<=ny<n and 0<=nx<m and not vistied[ny][nx] and graph[ny][nx]!=-1:
                    queue.append((ny,nx))
                    vistied[ny][nx] = True
        dist += 1
    raise Exception()

try:
    for i in range(N):
        for j in range(M):
            if box[i][j] == 0:
                vistied = [[False] * M for _ in range(N)]
                vistied[i][j] = True
                days = max(days, bfs(box, (i,j), N, M, vistied))
    print(days)
except Exception:
    print(-1)

# =============== 2안 (통과) ===============

queue = deque()
for i in range(N):
    for j in range(M):
        if box[i][j] == 1:
            queue.append((i,j))

def bfs(graph, queue, n, m):
    dy = [0,1,0,-1]
    dx = [-1,0,1,0]

    while queue:
        y,x = queue.popleft()
        for i in range(4):
            ny,nx = y+dy[i],x+dx[i]
            if 0<=ny<n and 0<=nx<m and graph[ny][nx]==0:
                graph[ny][nx] = graph[y][x] + 1
                queue.append((ny,nx))

bfs(box, queue, N, M)
for i in range(N):
    for j in range(M):
        if box[i][j] == 0:
            print(-1)
            exit(0)
        days = max(days, box[i][j])
print(days-1)
저작자표시 (새창열림)

'Tech > Algorithm' 카테고리의 다른 글

[백준 1308] D-Day (Python)  (0) 2022.08.26
[백준 7569] 토마토 (Python)  (0) 2022.08.25
[백준 18870] 좌표 압축 (Python)  (0) 2022.08.24
[백준 1931] 회의실 배정 (Python)  (0) 2022.08.23
[백준 15686] 치킨 배달 (Python)  (0) 2022.08.23
    'Tech/Algorithm' 카테고리의 다른 글
    • [백준 1308] D-Day (Python)
    • [백준 7569] 토마토 (Python)
    • [백준 18870] 좌표 압축 (Python)
    • [백준 1931] 회의실 배정 (Python)
    minyeamer
    minyeamer
    Better than Yesterday

    티스토리툴바