DevYoon
[SWEA] 5656. ๋ฒฝ๋ ๊นจ๊ธฐ (Python) ๋ณธ๋ฌธ
link ๐ https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWXRQm6qfL0DFAUo
1๏ธโฃ DFS๋ก ์น ๋ฒฝ๋ ๊ณ ๋ฅด๊ธฐ
2๏ธโฃ BFS๋ก ๋ฒฝ๋์ ์ฐ์ฌ ์๋ ๋งํผ ์ํ์ข์ฐ ์ ๊ฑฐ
3๏ธโฃ gravity() ํจ์๋ก ๋ฒฝ๋ ๋ด๋ ค์ฃผ๊ธฐ, for๋ฌธ ์ฌ์ฉ
from collections import deque
import copy
# ์ค๋ ฅ์ ๋ฐ๋ผ ๋ฒฝ๋ ๋ด๋ ค์ฃผ๊ธฐ
def gravity():
for j in range(W):
for i in range(H-1, 0, -1): # H-1 ~ 1๊น์ง ๊ฑฐ๊พธ๋ก ํ์
if board[i][j] == 0: # 0์ ๋ง๋๋ฉด
for k in range(i-1, -1, -1): # ์์ชฝ์ผ๋ก ํ์
if board[k][j] != 0: # 0์ด ์๋ ์๋ฅผ ๋ง๋๋ฉด ์ค์
board[i][j], board[k][j] = board[k][j], board[i][j]
break
# ๋ฒฝ๋ ์ ๊ฑฐ
def bomb(y, x):
q = deque()
q.append((y, x, board[y][x]))
while q:
nowy, nowx, n = q.popleft()
board[nowy][nowx] = 0 # ํญํ ํฐ์ง๋ ์๋ฆฌ ๋ฒฝ๋ ์ ๊ฑฐ
directy = [-1, 1, 0, 0]
directx = [0, 0, -1, 1]
for i in range(n): # ๋ฒฝ๋์ ์ ํ ์ซ์ -1๋งํผ
for j in range(4):
dy = directy[j]*i+nowy # ๋ฒ์ ์ง์
dx = directx[j]*i+nowx
if 0 <= dy < H and 0 <= dx < W:
if board[dy][dx] != 0: # ๋ฒฝ๋์ด ์์ผ๋ฉด
q.append((dy, dx, board[dy][dx])) # q์ ์ถ๊ฐํ์ฌ ์์ ์ฃผ๊ธฐ
gravity()
# ๋จ์ ๋ฒฝ๋ ์ ์ธ๊ธฐ
def check():
cnt = 0
for i in range(H):
for j in range(W):
if board[i][j] != 0:
cnt += 1
return cnt
# dfs
def dfs(level):
global board, Min
if level == N:
ret = check()
if Min > ret:
Min = ret
return
backup = copy.deepcopy(board)
flag = 1
for j in range(W):
for i in range(H):
if board[i][j] != 0:
flag = 0
bomb(i, j)
dfs(level+1)
board = copy.deepcopy(backup)
break
# Level N ์ ์ ๋ฐฐ์ด ์์ ๋ฒฝ๋์ด ํ๋๋ ์์ผ๋ฉด
if flag:
Min = 0 # 0 ๋ฆฌํด
return
t = int(input())
for tc in range(1, t+1):
N, W, H = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(H)]
Min = 2e18
dfs(0)
print(f'#{tc} {Min}')
๐ฅ์ฃผ์
- W, H ์ ๊ตฌ๋ถ! ๋ ๋ฐ๊ฟ์ด์ง๋ ๋ชจ๋ฅด๊ณ ํ์ฐธ์ ๋๋ฒ๊น ...๐
- ๋ฒ์ ์ง์ ์ ํด์ฃผ๊ธฐ... ์ธ์ ๋ ์ ์ผ ํท๊ฐ๋ฆฌ๋ ์ธ๋ฑ์ค ๋ฒ์ ์ง์ ํด์ฃผ๊ธฐ...๐ฅฒ