λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 14620 - 꽃길

by HandHand 2021. 3. 14.

문제

λ°±μ€€ 온라인 저지 - 14620번

풀이 κ³Όμ •

λ°±νŠΈλž˜ν‚Ή 을 μ΄μš©ν•œ 탐색 λ¬Έμ œμž…λ‹ˆλ‹€.
총 3개의 씨앗을 심을 수 있으며 νŠΉμ • 씨앗을 심을 경우 λ¬Έμ œμ—μ„œ μ œμ‹œλœ μΈμ ‘ν•œ μœ„μΉ˜μ—λŠ” 씨앗을 심을 수 μ—†μŠ΅λ‹ˆλ‹€.

λ¬Έμ œμ—μ„œ μ‹­μž λͺ¨μ–‘μœΌλ‘œ 꽃이 ν”ΌκΈ° λ•Œλ¬Έμ— (1, 1) λΆ€ν„° μ‹œμž‘ν•΄μ„œ (N - 1, N - 1) κΉŒμ§€λ§Œ
탐색을 μˆ˜ν–‰ν•˜λ©΄ λœλ‹€λŠ” 것을 μ•Œ 수 μžˆμŠ΅λ‹ˆλ‹€.
각 격자의 칸듀을 μ΄μš©ν•΄μ„œ κ°€λŠ₯ν•œ λͺ¨λ“  쑰합을 λ§Œλ“€μ–΄λ³΄λ©΄ λ˜λŠ”λ°
μ΄λ•Œ ν•΄λ‹Ή μœ„μΉ˜μ— 씨앗을 심을 수 μžˆλŠ”μ§€ νŒλ‹¨ν•˜λŠ” ν•¨μˆ˜λ₯Ό ν•˜λ‚˜ μ •μ˜ν•΄μ„œ κ΅¬ν˜„ν•©λ‹ˆλ‹€.

탐색할 λ•Œ μ£Όμ˜ν•  점은 λ‹€μŒ μœ„μΉ˜λΆ€ν„° νƒμƒ‰ν•˜κΈ° μœ„ν•΄ (x, y) 값을 μž¬κ·€μ μœΌλ‘œ λ„˜κ²¨μ£ΌλŠ”λ°,
μ΄λ•Œ y κ°€ 끝에 도달할 경우(N - 2) λ‹€μ‹œ y μΆ• 탐색 μ‹œμž‘ 지점을 0으둜 μ΄ˆκΈ°ν™” μ‹œμΌœμ£Όμ–΄μ•Ό ν•œλ‹€λŠ” μ μž…λ‹ˆλ‹€.

μ½”λ“œ


import sys

N = int(input())
board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

dx = [1, -1, 0, 0, 0]
dy = [0, 0, 1, -1, 0]


def acc_flower(visit):
    acc = 0
    for x in range(N):
        for y in range(N):
            if visit[x][y]:
                acc += board[x][y]

    return acc


def is_acceptable(visit, x, y):
    for i in range(5):
        nx, ny = x + dx[i], y + dy[i]
        if visit[nx][ny]:
            return False

    return True


def set_flower(visit, x, y, val):
    for i in range(5):
        nx, ny = x + dx[i], y + dy[i]
        visit[nx][ny] = val


def dfs(visit, x, y, seed):
    if not seed:
        acc = acc_flower(visit)
        return acc

    ret = sys.maxsize
    for nx in range(x, N - 1):
        for ny in range(y, N - 1):
            if is_acceptable(visit, nx, ny):
                set_flower(visit, nx, ny, 1)
                ret = min(ret, dfs(visit, nx, ny, seed - 1))
                set_flower(visit, nx, ny, 0)
            # y좕이 끝에 λ„λ‹¬ν•˜λ©΄ 1둜 μ΄ˆκΈ°ν™”
            if ny == N - 2:
                y = 1

    return ret


def solution():
    answer = sys.maxsize

    for x in range(1, N - 1):
        for y in range(1, N - 1):
            visit = [[0] * N for _ in range(N)]
            set_flower(visit, x, y, 1)
            answer = min(answer, dfs(visit, x, y, 2))
            set_flower(visit, x, y, 0)

    return answer


print(solution())
λ°˜μ‘ν˜•

'πŸƒ algorithm > boj' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

BOJ 13164 - 행볡 μœ μΉ˜μ›  (0) 2021.03.14
BOJ 3109 - 빡집  (0) 2021.03.14
BOJ 2688 - 쀄어듀지 μ•Šμ•„  (0) 2021.03.14
BOJ 16472 - κ³ λƒ₯이  (0) 2021.03.14
BOJ 17086 - μ•„κΈ° 상어2  (0) 2021.03.08

πŸ’¬ λŒ“κΈ€