๋ฌธ์
https://www.acmicpc.net/problem/2573
ํ์ด
# ๋ฐฑ์ค 2573๋ฒ ๋ฌธ์ - ๋น์ฐ
from collections import deque
dx, dy = [0,0,-1,1], [1,-1,0,0]
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
def bfs(x, y):
q = deque()
q.append((x, y))
while q:
x, y = q.popleft()
visited[x][y] = 1
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if graph[nx][ny] > 0 and not visited[nx][ny]:
visited[nx][ny] = 1
q.append((nx, ny))
elif graph[nx][ny] == 0:
count[x][y] += 1
return 1
year = 0
while True:
visited = [[0]*m for _ in range(n)]
count = [[0]*m for _ in range(n)]
res = 0
for i in range(n):
for j in range(m):
if graph[i][j] > 0 and not visited[i][j]:
res += bfs(i,j)
# ๋น์ฐ ๊น๊ธฐ
for i in range(n):
for j in range(m):
if graph[i][j] > count[i][j]:
graph[i][j] -= count[i][j]
else:
graph[i][j] = 0
if res >= 2:
break
if res == 0:
year = 0
break
year += 1
print(year)
Python3 ์ผ๋ก ์ ์ถํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ์ฌ pypy3๋ก ์ ์ถํ์๋ค.
๋ฌธ์ ์์ ์ฃผ์ํด์ผ ํ ์ ์ ๋น์ฐ์ ๋ฐ๋ก ๊น์ง ์๋ ๊ฒ์ด๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Silver1] 2504๋ฒ_๊ดํธ์ ๊ฐ (0) | 2023.02.08 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 1068๋ฒ_ํธ๋ฆฌ (0) | 2023.01.04 |
๐ฉ [๋ฐฑ์ค] [Python] 13549๋ฒ_์จ๋ฐ๊ผญ์ง 3 (0) | 2022.12.17 |
๐ฉ [๋ฐฑ์ค] [Python] 24444๋ฒ_์๊ณ ๋ฆฌ์ฆ ์์ - ๋๋น ์ฐ์ ํ์ 1 (0) | 2022.12.16 |
๐ฉ [๋ฐฑ์ค] [Python] 24445๋ฒ_์๊ณ ๋ฆฌ์ฆ ์์ - ๋๋น ์ฐ์ ํ์ 2 (0) | 2022.12.16 |