File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+ from collections import deque
3+ input = sys .stdin .readline
4+ N , K = map (int , input ().split ())
5+ MAX = 100000
6+ # answer = []
7+ #[1] 최단 시간 찾기
8+ visited = [MAX ]* (MAX + 1 ) # level 기입
9+ t = 0
10+ next_node = [N ]
11+ q = deque ([N ])
12+ visited [N ] = t
13+ while q :
14+ t += 1
15+ next_node = len (q )
16+ for i in range (next_node ) : # 현재 level의 node개수만큼 반복
17+ cx = q .popleft ()
18+ # 만약 목적 달성시 , 끝
19+ for nx in [cx - 1 , cx + 1 , cx * 2 ]:
20+ if 0 <= nx <= MAX and visited [nx ]>= MAX :
21+ q .append (nx )
22+ visited [nx ] = t
23+ # 현재 q -> 다음 level 의 노드만 남아있는 상태
24+ # 만약 K을 도달한 경우-> 최단 시간 저장
25+ if visited [K ] < MAX :
26+ # answer.append(t)
27+ break
28+
29+ #[2]역추적K-> N - backtracking , DFS
30+ re_visited = []
31+ stack = deque ([[K ,t ]])
32+ while stack :
33+ cx , ct = stack .pop ()
34+ if cx not in re_visited :
35+ re_visited .append (cx )
36+ if cx == N :
37+ break
38+ if cx % 2 == 0 : #짝수면
39+ ad_li = [cx - 1 ,cx + 1 , cx // 2 ]
40+ else :
41+ ad_li = [cx - 1 , cx + 1 ]
42+ # print("##",ad_li , type(ad_li))
43+ for nx in ad_li :
44+ if 0 <= nx <= MAX and nx not in re_visited and visited [nx ] == ct - 1 :
45+ stack .append ([nx ,ct - 1 ])
46+ print (t )
47+ print (" " .join (map (str ,list (reversed (re_visited )))))
48+
You can’t perform that action at this time.
0 commit comments