λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 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 |
π¬ λκΈ