프로그래밍/코딩테스트

[BOJ] 숨바꼭질

매우빠른거부기 2022. 7. 21. 15:02

 

 

내 틀린 코드..

상처뿐인 코드.....

 

from collections import deque

n, k = map(int, input().split())

visited = [False]*(100001)

visited[k] = True
que = deque([k])
arr = [0]*3
cnt = 0
while que:
    cnt += 1
    tmp = que.popleft()
    if tmp == 0:
        continue
    if tmp - 1 >= 0:
        arr[0] = tmp - 1
    arr[1] = tmp + 1
    if tmp%2 == 0:
        arr[2] = tmp//2
    for i in arr:
        if not visited[i]:
            #print(i)
            que.append(i)
            visited[i] = True
    if visited[n] == True:
        break
answer = 0 
while cnt > 1:
    answer += 1 
    cnt = cnt//2
print(answer)

 

 

 

머리 좀 쓰겠다고 k에서 n으로 가게 하려고 했떤 나..라는 바보......

 

나대지 말고 그냥 popleft할 때부터 일단 k인지 확인하고 맞으면 break

아니면 고대로 아래로...

0과 max 값 사이인지 확인하고, 방문하지 않은 값만

지금까지 왔던 경로에서 +1 해준다....

이것은 단순히 True False로 하는 간단한 문제가 아니었따!!!!!!!!!!!!!!!!!!!

천재다... ㅠ

from collections import deque

def bfs():
    que = deque()
    que.append(n)
    while que:
        x = que.popleft()
        if x == k:
            print(dist[x])
            break
        for nx in (x-1, x+1, x*2):
            if 0<=nx<MAX and not dist[nx]:
                dist[nx] = dist[x]+1
                que.append(nx)
MAX = 100000
dist = [0]*(MAX+1)
n, k = map(int, input().split())

bfs()

https://wook-2124.tistory.com/273