Zero to Hero
Published 2021. 4. 15. 15:04
13549번: 숨바꼭질 3 Algorithm
 

13549번: 숨바꼭질 3

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

import sys
from collections import deque

r = sys.stdin.readline
src, dst = map(int, r().split())
visited = set()
q = deque([])
q.append((src, 0))

result = 0
while q:
    cur_pos, cur_val = q.popleft()
    if cur_pos == dst:
        result = cur_val
        break
    if 0 <= cur_pos * 2 <= 100002 and cur_pos * 2 not in visited:
        visited.add(cur_pos * 2)
        q.appendleft((cur_pos * 2, cur_val))
    if 0 <= cur_pos + 1 <= 100000 and cur_pos + 1 not in visited:
        visited.add(cur_pos + 1)
        q.append((cur_pos + 1, cur_val + 1))
    if 0 <= cur_pos - 1 <= 100000 and cur_pos - 1 not in visited:
        visited.add(cur_pos - 1)
        q.append((cur_pos - 1, cur_val + 1))

print(result)

이 문제의 정해는 0-1 BFS를 사용한 풀이다.

자세한 것은 링크를 참고.

 

[그래프] 0-1 BFS 알고리즘

어제 알고리즘에 대해 검색을 하다가 코드포스 블로그에서 흥미로운 최단경로 최적화법을 찾아서, 그 방법을 소개하고자 합니다.

justicehui.github.io

 

'Algorithm' 카테고리의 다른 글

7. Reverse Integer  (0) 2021.04.17
104. Maximum Depth of Binary Tree  (0) 2021.04.16
283. Move Zeroes  (0) 2021.04.15
787. Cheapest Flights Within K Stops  (0) 2021.04.14
763. Partition Labels  (0) 2021.04.13
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!