알고리즘

[백준] 16928번(python 파이썬)

changha. 2022. 8. 18. 12:43
bfs 특징
1. queue
2. visited 여부
3. 상하좌우 => 여기선 주사위(1~6)

from collections import deque

def bfs():
    q = deque([1])
    visited[1] = True
    while q:
        now = q.popleft()
        for i in range(1, 7):
            move = now + i
            if 0 < move <= 100 and not visited[move]:
                # 뱀과 사다리 만났을 때 최신화 
                if move in ladder.keys(): #key, value 
                    move = ladder[move]
                if move in snack.keys():
                    move = snack[move]
                
                if not visited[move]:
                    q.append(move)
                    visited[move] = True
                    board[move] = board[now] + 1
                    

N, M = map(int, input().split())
board = [0] * 101
visited = [False] * 101


ladder = dict()
snack = dict()

for _ in range(N):
    i, j = map(int, input().split())
    ladder[i] = j

for _ in range(M):
    i, j = map(int, input().split())
    snack[i] = j
    
bfs()
print(board[100])