728x90
๋ฌธ์
ํ์ด
DFS๋ฌธ์ , ๋ค๋ง ์กฐ๊ธ ๊น๋ค๋กญ๊ฒ ๊ตฌํํด์ผ ํ๋ค.
"๋ง์ผ ์ ๋ถ ๋ค ๋ น์ ๋๊น์ง ๋ ๋ฉ์ด๋ฆฌ ์ด์์ผ๋ก ๋ถ๋ฆฌ๋์ง ์์ผ๋ฉด ํ๋ก๊ทธ๋จ์ 0์ ์ถ๋ ฅํ๋ค." ํด๋น ์กฐ๊ฑด์ ๊ตฌํํ์ง ์์ 62%์์ ํ๋ ธ์ต๋๋ค๊ฐ ๋์๋ค.
[๋ฐ๋ก]
5 5
0 0 0 0 0
0 2 2 2 0
0 2 2 2 0
0 2 2 2 0
0 0 0 0 0
๋ต : 0
ํ๋ฆฐ ๋ต : 3
๋ํ DFS๋ก ํ ๊ฒฝ์ฐ
sys.setrecursionlimit(10**4)
setreucrsionlimit์ ๋๋ฌด ํฐ ๊ฐ์ ๋ฃ์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ๊ฐ ๋์จ๋ค. ์ฃผ์ํ ๊ฒ!!
์ฝ๋
import sys
sys.setrecursionlimit(10**4)
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
dir = ((0, 1), (0, -1), (1, 0), (-1, 0))
def check(i, j):
return i < 0 or i >= n or j < 0 or j >= m
def searchZero(i, j):
cnt = 0
for dy, dx in dir:
ni, nj = dy + i, dx + j
if check(ni, nj) or graph[ni][nj] != 0: continue
cnt += 1
return cnt
#๋น์ฐ ๋
น์
def melt():
meltStk = []
for i in range(n):
for j in range(m):
if graph[i][j] != 0:
meltStk.append((i, j, searchZero(i, j)))
for i, j, delIce in meltStk:
graph[i][j] -= delIce
if graph[i][j] < 0:
graph[i][j] = 0
#์ฐ๊ฒฐ๋ ๋น์ฐ ํ์
def dfs(i, j):
visited[i][j] = True
for dy, dx in dir:
ni, nj = dy + i, dx + j
if check(ni, nj) or visited[ni][nj] or not graph[ni][nj]: continue
dfs(ni, nj)
cnt = 0
while True:
visited = [[False] * m for _ in range(n)]
ice = 0
for i in range(n):
for j in range(m):
if not visited[i][j] and graph[i][j]:
dfs(i, j)
ice += 1
if ice == 1:
melt()
cnt += 1
continue
if ice == 0:
print(0)
break
print(cnt)
break
๋ง๋ฌด๋ฆฌ
dfs๋ ์ญ์ ์๊ฐ์ด ์ค๋ ๊ฑธ๋ฆฌ๋ ๊ฒ ๊ฐ๋ค.
728x90