DevYoon

[SWEA] 5656. ๋ฒฝ๋Œ ๊นจ๊ธฐ (Python) ๋ณธ๋ฌธ

PS/SWEA

[SWEA] 5656. ๋ฒฝ๋Œ ๊นจ๊ธฐ (Python)

gimewn 2022. 4. 6. 00:06

link ๐Ÿ”— https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWXRQm6qfL0DFAUo 

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

 

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 ์ž˜ ๊ตฌ๋ถ„! ๋‘˜ ๋ฐ”๊ฟ”์“ด์ง€๋„ ๋ชจ๋ฅด๊ณ  ํ•œ์ฐธ์„ ๋””๋ฒ„๊น…...๐Ÿ™ƒ
  • ๋ฒ”์œ„ ์ง€์ • ์ž˜ ํ•ด์ฃผ๊ธฐ... ์–ธ์ œ๋‚˜ ์ œ์ผ ํ—ท๊ฐˆ๋ฆฌ๋Š” ์ธ๋ฑ์Šค ๋ฒ”์œ„ ์ง€์ •ํ•ด์ฃผ๊ธฐ...๐Ÿฅฒ