๐๋ฌธ์
https://www.acmicpc.net/problem/7576
๐์ด๋ค ์๊ณ ๋ฆฌ์ฆ?
1. ์ธ์ ํ ์นธ์ ์ต๊ฒ ๋ง๋ ๋ค๊ณ ํ์ผ๋ฏ๋ก ๋น์ฐํ bfs๋ฅผ ์ฌ์ฉํ๋ค. (bfs๋?)
2. ์ด ๋ฌธ์ ์ ๊ฐ์ด ์์์ ์ด ์ฌ๋ฌ๊ฐ์ธ ๋ฌธ์ ๋ ํ์ ์์์ ์ ๋ชจ๋ ๋ฃ๊ณ ๋์ bfs๋ฅผ ๋๋ฆฌ๋ ๊ฒ์ด ํต์ฌ์ด๋ค.
๐ป์ฝ๋
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() # ํ ์ค์
# ํ์ ์์, ์ต์ ํ ๋งํ ์ขํ ํ์ ๋ฃ์ด๋๊ธฐ
#(0:์์ต์ ํ ๋งํ , 1:์ต์ ํ ๋งํ )
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 > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 9498 ์ํ ์ฑ์ (ํ์ด์ฌ/python) (0) | 2023.06.19 |
---|---|
[๋ฐฑ์ค] 1330 ๋ ์ ๋น๊ตํ๊ธฐ (ํ์ด์ฌ/python) (0) | 2023.06.19 |
[๋ฐฑ์ค] 4179 ๋ถ! (ํ์ด์ฌ/python) (with ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ) (1) | 2023.06.19 |
[๋ฐฑ์ค] 2178 ๋ฏธ๋ก (ํ์ด์ฌ/python) (0) | 2023.06.19 |
[๋ฐฑ์ค] 1926 ๊ทธ๋ฆผ (ํ์ด์ฌ/python) (0) | 2023.06.17 |