Algorithm: BFS(Breadth First Search)

calico·2025년 8월 10일

Algorithm

목록 보기
7/16

1. [백준] 7576 토마토

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


좌표만 저장




from collections import deque

m, n = map(int, input().split())
box = [list(map(int, input().split())) for _ in range(n)]

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

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

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

bfs()

result = 0
for tomatoes in box:
    for tomato in tomatoes:
        if tomato == 0:
            print(-1)
            raise SystemExit  # ← sys 없이 종료
    result = max(result, max(tomatoes))

print(result - 1)





경과일도 저장


from collections import deque

m, n = map(int, input().split())           # m: 열(가로, y), n: 행(세로, x)
box = [list(map(int, input().split())) for _ in range(n)]

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

queue = deque()
unripe = 0

# 시작점 수집 & 안 익은 개수 카운트
for x in range(n):
    for y in range(m):
        if box[x][y] == 1:
            queue.append((x, y, 0))
        elif box[x][y] == 0:
            unripe += 1

# 이미 전부 익었으면 0일
if unripe == 0:
    print(0)
    raise SystemExit

max_days = 0

while queue:
    x, y, d = queue.popleft()
    for i in range(4):
        nx, ny = x + dx[i], y + dy[i]
        if 0 <= nx < n and 0 <= ny < m and box[nx][ny] == 0:
            box[nx][ny] = 1   
            unripe -= 1
            nd = d + 1
            if nd > max_days:
                max_days = nd
            queue.append((nx, ny, nd))

print(-1 if unripe > 0 else max_days)




2. [백준] 7579 토마토

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




from collections import deque
import sys

m, n, h = map(int, sys.stdin.readline().split())  
box = [[list(map(int, sys.stdin.readline().split())) for _ in range(n)] for _ in range(h)]


dirs = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]

queue = deque()
for z in range(h):
    for y in range(n):
        for x in range(m):
            if box[z][y][x] == 1:
                queue.append((z, y, x))

while queue:
    z, y, x = queue.popleft()
    for dz, dy, dx in dirs:
        nz, ny, nx = z + dz, y + dy, x + dx
        if 0 <= nz < h and 0 <= ny < n and 0 <= nx < m and box[nz][ny][nx] == 0:
            box[nz][ny][nx] = box[z][y][x] + 1
            queue.append((nz, ny, nx))

result = 0
for z in range(h):
    for y in range(n):
        if 0 in box[z][y]:
            print(-1)
            raise SystemExit
        result = max(result, max(box[z][y]))

print(result - 1)




3. [백준] 1697 숨바꼭질

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



from collections import deque

n, k = map(int, input().split())
# 움직일 수 있는 최대 좌표
max_num = 100000
visited = [0] * (max_num + 1) 

def bfs():
    queue = deque()
    queue.append(n)
    while q:
        x = queue.popleft()
        # 수빈이 위치가 동생의 위치와 같다면 반복문 종료
        if x == k:
            print(visited[x])
            break

        for i in (x-1, x+1, x*2):
            if 0 <= i <= max_num and not visited[i]:
                visited[i] = visited[x] + 1
                queue.append(i)
bfs()



profile
All views expressed here are solely my own and do not represent those of any affiliated organization.

0개의 댓글