[백준 BFS] 숨바꼭질 2(python)

이진규·2023년 3월 23일
1

백준(PYTHON)

목록 보기
114/115

문제

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

나의 코드

from sys import stdin
input = stdin.readline

from collections import deque

N, M = map(int, input().split())
time = [-1] * 100001
cnt = [0] * 100001

def bfs(v, step):

    q = deque([(v, step)])

    while q:

        v, step = q.popleft()

        for x in (v-1, v+1, 2*v):
            if 0 <= x <= 100000:
                if time[x] == -1:
                    time[x] = step+1
                    cnt[x] += 1
                    q.append((x, step+1))
                elif time[x] == step+1:
                    cnt[x] += 1
                    q.append((x, step+1))

time[N] = 0
cnt[N] = 1
bfs(N, 0)

print(time[M])
print(cnt[M])    

배운점

숨바꼭질 문제와 다르게 '가능한 방법의 개수'까지 출력해야 하므로 도착지(M)에 도착했더라도 멈추지 않고 cnt라는 개수를 세는 배열을 만들어 끝까지 세주어야 한다.

profile
항상 궁금해하고 공부하고 기록하자.

0개의 댓글