728x90
반응형
기본적인 그래프 탐색 문제이다. 최단거리를 찾는 문제이므로 BFS로 풀었다.
from collections import deque
def bfs():
q = deque()
q.append((0))
while q:
node = q.popleft()
n = li[node]
if check[n] == 0 and node != n:
q.append(n)
check[n] = check[node] + 1
if n == K:
return ;
N, K = map(int, input().split())
li = [int(input()) for _ in range(N)]
check = [0]*N
bfs()
print(check[K] if check[K] else -1)
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 9311번 Robot in a Maze(python) (0) | 2021.12.22 |
---|---|
백준 알고리즘 11256번 사탕(python) (0) | 2021.10.26 |
백준 알고리즘 16173번 점프왕 쩰리 (Small)(python) (0) | 2021.10.21 |
백준 알고리즘 3182번 한동이는 공부가 하기 싫어!(python) (0) | 2021.08.10 |
백준 알고리즘 14888번 연산자 끼워넣기(python) (0) | 2021.08.08 |