[Python][DFS]숨바꼭질

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# def bfs(n, k):
#     global MAX_VAL
#     time = 0
#     queue = deque()
#     queue.append((n,time))
#     check[n] = True
#     while queue:
#         curr_p, curr_t = queue.popleft()
#         for d in [-1, +1, curr_p]:
#             next_p = curr_p + d
#             if not check[next_p] and 0<=next_p<=MAX_VAL:
#                 if next_p == k:
#                     print(curr_t+1)
#                     return
#                 queue.append((next_p, curr_t+1))
#                 check.append(next_p)

from collections import deque

MAX_VAL = 100000
check = [False] * (MAX_VAL+1)
dist = [-1]*(MAX_VAL+1)
n, k = map(int, input().split())
check[n] = True
dist[n] = 0
q = deque()
q.append(n)
while q:
    curr_p = q.popleft()
    for next_p in [curr_p-1, curr_p+1, 2*curr_p]:
        if 0 <= next_p <= MAX_VAL and check[next_p] == False:
            check[next_p] = True
            dist[next_p] = dist[curr_p]+1
            q.append(next_p)

print(dist[k])

댓글

이 블로그의 인기 게시물

[python]섬의 둘레구하기

백트래킹으로 부분집합구하기(Get Powerset usiing Backtracking)

[패턴매칭][Python]보이어 무어 알고리즘