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

BOJ 15684 - 사닀리 μ‘°μž‘

by HandHand 2021. 6. 7.

문제

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

풀이 κ³Όμ •

DFS 와 λ°±νŠΈλž˜ν‚Ή 을 ν™œμš©ν•œ μ΅œμ ν™”κ°€ ν•„μš”ν•œ 탐색 λ¬Έμ œμž…λ‹ˆλ‹€.

μ΄λ•Œ μ‚¬λ‹€λ¦¬μ˜ μœ„μΉ˜λ₯Ό κ²€μ‚¬ν•˜λŠ” κ³Όμ •μ—μ„œ 인덱슀 λ²”μœ„μ— λŒ€ν•œ κ³ λ €λ₯Ό μ•ˆν•΄μ£ΌκΈ° μœ„ν•΄ board μ–‘μͺ½μ— padding 을 μΆ”κ°€ν–ˆμŠ΅λ‹ˆλ‹€.
μ΄λ ‡κ²Œ μ•ˆν•˜λ©΄ μ–‘μͺ½ 사닀리 μœ„μΉ˜ μΈλ±μŠ€κ°€ board λ₯Ό λ²—μ–΄λ‚˜λŠ”μ§€μ— λŒ€ν•œ 쑰건문에 μΆ”κ°€ν•΄μ€˜μ„œ μ½”λ“œκ°€ λ³΅μž‘ν•΄μ§‘λ‹ˆλ‹€.
사닀리λ₯Ό 2차원 λ°°μ—΄λ‘œ ν‘œν˜„ν–ˆμœΌλ―€λ‘œ 각 μ‹œμž‘μ μ—μ„œ 타고 λ‚΄λ €μ˜¬λ•ŒλŠ” μ™Όμͺ½, 였λ₯Έμͺ½μ—μ„œ λ§Œλ‚˜λŠ” 경우λ₯Ό κ³ λ €ν•΄μ€˜μ•Ό ν•©λ‹ˆλ‹€.
μ£Όμ˜ν•  점은 μˆ˜ν‰ λ°©ν–₯으둜 μ΄λ™ν–ˆμ„ κ²½μš°μ—λŠ” λ°”λ‘œ ν•œμΉΈ λ°‘μœΌλ‘œ μ „μ§„μ‹œμΌœμ€˜μ•Όν•©λ‹ˆλ‹€. (μ•ˆκ·ΈλŸ¬λ©΄ λ¬΄ν•œ 루프에 λΉ μ§‘λ‹ˆλ‹€.)

DFS λ₯Ό μˆ˜ν–‰ν•˜λŠ” κ³Όμ •μ—μ„œ λ§Œμ•½ λ§Œμ‘±ν•˜λŠ” 쑰합을 μ°Ύμ•˜μ„ κ²½μš°μ—λŠ” 이후 탐색을 μˆ˜ν–‰ν•˜μ§€ μ•Šκ³ 
λ°”λ‘œ True λ₯Ό λ°˜ν™˜ν•˜λ„λ‘ ν•΄μ„œ λΆˆν•„μš”ν•œ 탐색을 μ€„μ˜€μŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys

N, M, H = list(map(int, sys.stdin.readline().split()))
ladders = []
for i in range(M):
    ladders.append(list(map(int, sys.stdin.readline().split())))


def match(board):
    for start in range(1, N+1):
        cur = [0, start]

        while cur[0] < H:
            # μ™Όμͺ½μ—μ„œ λ§Œλ‚  경우
            if board[cur[0]][cur[1]]:
                cur = [cur[0], cur[1] + 1]
            # 였λ₯Έμͺ½μ—μ„œ λ§Œλ‚  경우
            elif board[cur[0]][cur[1]-1]:
                cur = [cur[0], cur[1] - 1]

            cur[0] += 1

        if cur[1] != start:
            return False
    return True


def dfs(board, depth, goal):
    if depth == goal:
        return match(board)

    ret = False
    for r in range(H):
        for c in range(1, N):
            if board[r][c] != 1 and board[r][c-1] != 1 and board[r][c+1] != 1:
                board[r][c] = 1
                ret = dfs(board, depth+1, goal)
                if ret:
                    return True
                board[r][c] = 0
    return ret


def solution():
    # board μ΄ˆκΈ°ν™”
    board = [[0 for _ in range(N+2)] for _ in range(H)]  # μ–‘μͺ½μ— padding
    for ladder in ladders:
        board[ladder[0]-1][ladder[1]] = 1

    for i in range(4):
        if dfs(board, 0, i):
            return i

    return -1


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

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

BOJ 2231 - λΆ„ν•΄ν•©  (0) 2021.06.07
BOJ 1916 - μ΅œμ†ŒλΉ„μš© κ΅¬ν•˜κΈ°  (0) 2021.06.07
BOJ 1781 - 컡라면  (0) 2021.06.07
BOJ 6118 - μˆ¨λ°”κΌ­μ§ˆ  (0) 2021.06.07
BOJ 2331 - λ°˜λ³΅μˆ˜μ—΄  (0) 2021.06.07

πŸ’¬ λŒ“κΈ€