본문 바로가기
Python/DFS&BFS

99클럽 코테 스터디 7일차 TIL + 백준 1697 숨바꼭질 (파이썬)

by 유일리 2025. 1. 21.

※ 1697 숨바꼭질

https://www.acmicpc.net/problem/1697

문제 해결 TIP

문제에 주어진 대로 x - 1, x + 1, x * 2 총 3가지 방법이 있다. 동생의 점 K와 같을 때까지 반복하며, 시간은 dist 배열을 통해 1씩 추가해주며 구한다.

 

전체 코드

from collections import deque

N, K = map(int,input().split())

def bfs():
    queue = deque()
    queue.append(N)
    while queue:
        x = queue.popleft()
        if x == K:
            print(dist[x])
            break
        for i in (x - 1, x + 1, x * 2):
            if 0 <= i <= 100000 and not dist[i]:
                dist[i] = dist[x] + 1
                queue.append(i)

dist = [0] * 100001
bfs()

댓글