๐๋ฌธ์
https://www.acmicpc.net/problem/7569
๐์ด๋ค ์๊ณ ๋ฆฌ์ฆ?
1. ์ธ์ ํ ํ ๋งํ ๊ฐ ์ต๊ฒ ๋ง๋๋ฏ๋ก bfs๋ฅผ ์ฌ์ฉํด์ผ๊ฒ ๋ค๊ณ ํ๋จํจ
2. ์์์ ์ด ์ฌ๋ฌ๊ฐ์ธ bfs ๋ฌธ์ ์ ๊ฒฝ์ฐ, ์์์ ์ ๋ชจ๋ ํ์ ๋ฃ๊ณ bfs๋ฅผ ๋๋ฆฌ๋ ๊ฒ์ด ํต์ฌ์ด๋ค.
๐ป์ฝ๋
# 7576 ํ ๋งํ
from collections import deque
def bfs():
# ์ํ์ข์ฐ ์ขํ ์ค์
dx = [0,0,-1,1]
dy = [1,-1,0,0]
while deq:
x,y = deq.popleft() # ํ์์ ์ต์ ํ ๋งํ ์ขํ ๊บผ๋ด๊ธฐ
for i in range(4): # ์ํ์ข์ฐ ํ์ ์์
nx = x + dx[i]
ny = y + dy[i]
# graph ๋ฒ์ด๋ ์ขํ๋ ๋ฌด์
if nx < 0 or nx > (n-1) or ny < 0 or ny > (m-1):
continue
if graph[nx][ny] == 0: # ์์ต์ ํ ๋งํ ๋ฐ๊ฒฌ
graph[nx][ny] = graph[x][y] + 1 # ๋ ์ง+1
deq.append([nx,ny])
# n: ์ธ๋ก(x), m: ๊ฐ๋ก(y)
m,n = map(int,input().split())
#graph
graph = []
for i in range(n):
graph.append(list(map(int,input().split())))
deq = deque() # ํ ์ค์
# ํ์ ์์
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
deq.append([i,j])
# bfs๋๋ ค์ ํ ๋งํ ์ตํ๊ธฐ
bfs()
# ์ต์ง ๋ชปํ๋ ํ ๋งํ ํ์ธ ๋ฐ ๊ฑธ๋ฆฌ๋ ๋ ์ง ํ์ธ
all_ripe = True # ํ ๋งํ ๊ฐ ๋ชจ๋ ์ต์๋์ง ํ์ธํ ๋ณ์
day = 0 # ํ ๋งํ ๊ฐ ๋ชจ๋ ์ต์ ๋๊น์ง์ ์ต์ ๋ ์ง
for i in range(n):
for j in range(m):
if graph[i][j] == 0: # ์์ง ์์ต์ ํ ๋งํ ๊ฐ ์กด์ฌํ๋ฉด
all_ripe = False
print(-1)
break
day = max(day,graph[i][j])
if not all_ripe:
break
if all_ripe: # ํ ๋งํ ๋ชจ๋ ์ต์์ผ๋ฉด
print(day-1)
'Algorithm > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2194 ์ ๋ ์ด๋์ํค๊ธฐ (ํ์ด์ฌ/python) bfs (0) | 2023.08.14 |
---|---|
[๋ฐฑ์ค] 1463 1๋ก ๋ง๋ค๊ธฐ (ํ์ด์ฌ/python) dp, bfs (0) | 2023.08.03 |
[๋ฐฑ์ค] 1992 ์ฟผ๋ํธ๋ฆฌ (ํ์ด์ฌ/python) (0) | 2023.07.12 |
[๋ฐฑ์ค] 12904 A์ B (ํ์ด์ฌ/python) (0) | 2023.07.11 |
[๋ฐฑ์ค] 7562 ๋์ดํธ์ ์ด๋ (ํ์ด์ฌ/python) (0) | 2023.07.11 |