Algorithm/๋ฐฑ์ค
[๋ฐฑ์ค] 2638 ์น์ฆ(ํ์ด์ฌ/python)
chjcoder
2023. 8. 18. 14:08
๐๋ฌธ์
https://www.acmicpc.net/problem/2638
๐์๊ณ ๋ฆฌ์ฆ ๋ฐ ์ ๊ทผ
bfs
1. ์ธ๋ถ๊ณต๊ธฐ์ ๋ด๋ถ๊ณต๊ธฐ๋ฅผ ํ๋จ์ ๋จผ์ ํด์ผ ๋ น์ ์น์ฆ์ธ์ง ์๋์ง๋ฅผ ํ๋จํ ์ ์์๋ค.
๋ฐ๋ผ์ ๋ค์๊ณผ ๊ฐ์ ์์๋ก ์ฝ๋๋ฅผ ์ง๊ธฐ๋ก ํ๋ค.
1) ์ธ๋ถ๊ณต๊ธฐ / ๋ด๋ถ๊ณต๊ธฐ ํ๋จ
2) ๋ น์ ์น์ฆ ํ๋จ
3) ํ๋๋ผ๋ ๋ น์ผ๋ฉด ์๊ฐ +1
2. ์ธ๋ถ๊ณต๊ธฐ / ๋ด๋ถ๊ณต๊ธฐ ํ๋จ
(0,0)์ ๊ฐ์ฅ์๋ฆฌ์ด๋ฏ๋ก ๋ฌด์กฐ๊ฑด ์ธ๋ถ๊ณต๊ธฐ์ด๋ค. ๋ฐ๋ผ์ (0,0)๋ถํฐ bfs๋ฅผ ๋๋ฆฌ๋ฉด "์ธ๋ถ๊ณต๊ธฐ"์ "์น์ฆ&๋ด๋ถ๊ณต๊ธฐ" ๋ก ๋๋๋ค.
3. ๋ น์ ์น์ฆ ํ๋จ
์ธ๋ถ๊ณต๊ธฐ์ ๋ด๋ถ๊ณต๊ธฐ๊ฐ ํ๋จ๋๋ฉด, ์ํ์ข์ฐ๋ฅผ ์ดํด ์ธ๋ถ๊ณต๊ธฐ๊ฐ 2๊ฐ ์ด์์ด๋ฉด ์น์ฆ๋ฅผ ๋ น์ธ๋ค.
4. ๋ฐ๋ณต
๐ป์ฝ๋
# 2638 ์น์ฆ
from collections import deque
def Check(x,y):
dx = [0,0,1,-1]
dy = [1,-1,0,0]
cnt = 0
for i in range(4): # ์ํ์ข์ฐ ๊ณต๊ธฐ ์ฒดํฌ
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx > (n-1) or ny < 0 or ny > (m-1):
continue
if air_graph[nx][ny] == 1: # ์ธ๋ถ ๊ณต๊ธฐ์ด๋ฉด cnt + 1
cnt += 1
if cnt > 1: # 1์๊ฐ ๋ค ๋
น์ ์น์ฆ๋ฉด
graph[x][y] = 0 # ์น์ฆ ๋
น์ด๊ธฐ
return True
return False
# ์ธ๋ถ ๊ณต๊ธฐ ์ ๋ถ 1๋ก ํ์
def Air():
deq = deque()
deq.append([0,0])
air_graph[0][0] = 1
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]
if nx < 0 or nx > (n-1) or ny < 0 or ny > (m-1):
continue
if graph[nx][ny] == 0 and air_graph[nx][ny] == 0:
air_graph[nx][ny] = 1
deq.append([nx,ny])
return
# 1. ์
๋ ฅ ๋ฐ๊ธฐ
n,m = map(int,input().split())
graph = []
for i in range(n):
graph.append(list(map(int,input().split())))
time = 0
cheese = True
while cheese: # ์น์ฆ๊ฐ ๋
น์ ๋๋ง๋ค ์ธ๋ถ/๋ด๋ถ๊ณต๊ธฐ๊ฐ ๋ฐ๋
cheese = False
air_graph = [[0 for j in range(m)] for i in range(n)] # ๋ด๋ถ / ์ธ๋ถ ๊ณต๊ธฐ ํ๋จ
Air() # ๊ฐ์ฅ์๋ฆฌ๋ ์ธ๋ถ๊ณต๊ธฐ๋๊น ๊ฐ์ฅ์๋ฆฌ๋ถํฐ bfs ๋๋ ค๋ฒ๋ฆฌ๋ฉด ๋ค ์ธ๋ถ๊ณต๊ธฐ์ธ 1๋ก ์ฑ์์ง
for i in range(n):
for j in range(m):
if graph[i][j] == 1: # ์น์ฆ๋ฅผ ๋ง๋๋ฉด
if Check(i,j): # ํ ์๊ฐ ๋ค ๋
น์ ์น์ฆ์ธ์ง ํ๋จํ๊ณ ๋
น์ด๊ธฐ
cheese = True # ์น์ฆ ํ๋๋ผ๋ ๋
น์ผ๋ฉด True
if cheese: # ์น์ฆ๊ฐ ํ๋๋ผ๋ ๋
น์์ผ๋ฉด
time += 1 # ์๊ฐ ์ถ๊ฐ
print(time)
๐์ฝ๋ ์ค๋ช
์์ ์ฝ๋์ ์ฃผ์์ผ๋ก ๋์ฒดํ๋ค.