-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ_1326.java
More file actions
61 lines (47 loc) · 1.6 KB
/
BOJ_1326.java
File metadata and controls
61 lines (47 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.*;
import java.util.*;
public class BOJ_1326 {
static int N;
static int[] arr;
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
visited = new boolean[N];
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int result = bfs(a-1, b-1);
System.out.println(result);
}
static int bfs(int start, int target) {
Deque<int[]> q = new ArrayDeque<>();
q.add(new int[] {start, 0});
while(!q.isEmpty()) {
int[] v = q.poll();
int idx = v[0];
int step = arr[idx];
if (idx == target) return v[1];
for (int i = idx; i < N; i+=step) {
// if (i == target) return v[1]+1;
if (!visited[i]) {
q.add(new int[] {i, v[1] + 1});
visited[i] = true;
}
}
for (int i = idx; i >= 0; i-=step) {
// if (i == target) return v[1]+1;
if (!visited[i]) {
q.add(new int[] {i, v[1] + 1});
visited[i] = true;
}
}
}
return -1;
}
}