[백준/BOJ][Python] 1697번 숨바꼭질

Eunding·2024년 12월 5일
0

algorithm

목록 보기
63/107

1697번 숨바꼭질

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


아이디어

너무 간단한 BFS 문제인데 어처구니 없는 실수로 틀렸다
수빈이가 갈 수 있는 모든 경우를 살펴보면 되는데 내가 했던 실수는

for i in (x-1, x+1, 2*x):
	if 0 <= i <= MAX and graph[i] == 0:
		graph[i] = graph[x]+1
		queue.append(i)

저 if부분이다 위 코드처럼 i의 범위를 확인하고 graph[i] == 0인지 확인해야하는데 두 조건을 반대로 썼더니 계속 인덱스 에러가 났다.


코드

from collections import deque

def bfs(n, k):
    global MAX
    queue = deque([n])

    while queue:
        x = queue.popleft()
        if x == k:
            break
        for i in (x-1, x+1, 2*x):
            if 0 <= i <= MAX and graph[i] == 0:
                graph[i] = graph[x]+1
                queue.append(i)

    return graph[k]

n, k = map(int, input().split())
MAX = 10**5
graph= [0]*(MAX+1)
print(bfs(n, k))

0개의 댓글