Skip to content

Commit 9a519e1

Browse files
learntosurfMingguriguri
authored andcommitted
[BOJ] #1326.폴짝폴짝 / 실버2 / 60(X)
1 parent 0567ae7 commit 9a519e1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import sys
2+
input = sys.stdin.readline
3+
from collections import deque
4+
5+
N = int(input())
6+
arr = [0] + list(map(int, input().split())) # 1-based index 사용
7+
a, b = map(int, input().split())
8+
9+
def bfs(N, arr, a, b):
10+
queue = deque([(a, 0)]) # (현재 위치, 점프 횟수)
11+
visited = [False] * (N + 1) # 방문 여부 체크
12+
visited[a] = True # 시작점 방문 처리
13+
14+
while queue:
15+
pos, jump = queue.popleft()
16+
17+
# 목표 지점에 도달하면 점프 횟수 반환
18+
if pos == b:
19+
return jump
20+
21+
step = arr[pos] # 현재 위치에서 이동할 수 있는 거리
22+
if step == 0:
23+
continue # 이동할 수 없는 경우는 다음 탐색을 진행
24+
25+
# 양방향 탐색 (오른쪽 방향)
26+
next_pos = pos + step # 첫 번째 점프
27+
while next_pos <= N:
28+
if not visited[next_pos]: # 방문하지 않은 곳만 탐색
29+
if next_pos == b: # 목표 지점에 도달하면 즉시 반환
30+
return jump + 1
31+
visited[next_pos] = True
32+
queue.append((next_pos, jump + 1)) # 점프 횟수 증가
33+
next_pos += step # 다음 배수 위치 탐색
34+
35+
# 양방향 탐색 (왼쪽 방향)
36+
next_pos = pos - step # 왼쪽 방향 점프
37+
while next_pos >= 1:
38+
if not visited[next_pos]: # 방문하지 않은 곳만 탐색
39+
if next_pos == b: # 목표 지점에 도달하면 즉시 반환
40+
return jump + 1
41+
visited[next_pos] = True
42+
queue.append((next_pos, jump + 1)) # 점프 횟수 증가
43+
next_pos -= step # 다음 배수 위치 탐색
44+
45+
46+
# 목표 지점에 도달하지 못하면 -1 반환
47+
return -1
48+
49+
print(bfs(N, arr, a, b))

0 commit comments

Comments
 (0)