๋ฌธ์
https://www.acmicpc.net/problem/2638
ํ์ด
# ๋ฐฑ์ค 2638๋ฒ ๋ฌธ์ - ์น์ฆ
from collections import deque
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
dx, dy = [0,0,-1,1],[1,-1,0,0]
def bfs():
q = deque()
visited = [[0]*m for _ in range(n)]
q.append((0,0))
visited[0][0] = 1
while q:
x, y = q.popleft()
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]:
q.append((nx, ny))
visited[nx][ny] = 1
elif graph[nx][ny] == 1:
visited[nx][ny] += 1
melted = []
for i in range(n):
for j in range(m):
if visited[i][j] >= 2:
melted.append((i,j))
return melted
answer = 0
while True:
melted = bfs()
if not melted:
break
answer += 1
for x, y in melted:
graph[x][y] = 0
print(answer)
BFS ๋ฌธ์ ๋ผ๋ ๊ฒ์ ๋ฐ๋ก ์์๋๋ฐ ๋ด๋ถ ์น์ฆ๋ฅผ ํด๊ฒฐํ๋๋ฐ ์ค๋ ์๊ฐ์ ํ๋ค.
์น์ฆ๊ฐ ๋ น๋ ์กฐ๊ฑด์ ์ธ๋ถ ๊ณต๊ธฐ 2๋ฒ์ด์ ์ ์ดํ๋ ๊ฒ์ธ๋ฐ ๋ชจ๋ ํ์ํ๋ฉด์ visited ๊ฐ 2๋ฒ ์ด์ ๋ฐฉ๋ฌธํ๋ค๋ฉด ์น์ฆ๊ฐ ๋ น๋ ๊ฒ์ด๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2470๋ฒ_๋ ์ฉ์ก (0) | 2023.04.30 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2565๋ฒ_์ ๊น์ค (0) | 2023.04.29 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2225๋ฒ_ํฉ ๋ถํด (0) | 2023.04.27 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 1916๋ฒ_์ต์๋น์ฉ ๊ตฌํ๊ธฐ (0) | 2023.04.27 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 5582๋ฒ_๊ณตํต ๋ถ๋ถ ๋ฌธ์์ด (0) | 2023.04.26 |