Skip to content

Commit 43508dd

Browse files
committed
14248 점프 점프
1 parent 6e94ae6 commit 43508dd

File tree

1 file changed

+34
-35
lines changed

1 file changed

+34
-35
lines changed

src/main/java/bfs/silver/silver_2/_14248.java

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,11 @@
77

88
public class _14248 {
99

10-
static int n, count;
11-
static int[] graph;
12-
static boolean[] visited;
13-
static int[] dx = {1, -1}; // 좌, 우 이동 가능
10+
private static int n;
11+
private static int count;
1412

15-
private static void bfs(int start) {
16-
17-
Queue<Integer> queue = new LinkedList<>();
18-
queue.offer(start);
19-
visited[start] = true;
20-
21-
while (!queue.isEmpty()) {
22-
int pos = queue.poll();
23-
24-
for (int i = 0; i < 2; i++) {
25-
int nx = pos + (dx[i] * graph[pos]);
26-
27-
if (nx < 0 || nx >= n) {
28-
continue;
29-
}
30-
31-
if (!visited[nx]) {
32-
visited[nx] = true;
33-
queue.offer(nx);
34-
count++;
35-
}
36-
}
37-
}
38-
39-
}
13+
private static int[] stones;
14+
private static boolean[] visited;
4015

4116
public static void main(String[] args) throws IOException {
4217
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
@@ -45,21 +20,45 @@ public static void main(String[] args) throws IOException {
4520

4621
n = Integer.parseInt(br.readLine());
4722

48-
graph = new int[n];
23+
stones = new int[n];
4924
visited = new boolean[n];
5025

5126
st = new StringTokenizer(br.readLine());
52-
for (int i = 0; i < n; i++) graph[i] = Integer.parseInt(st.nextToken());
27+
for (int i = 0; i < n; i++) {
28+
stones[i] = Integer.parseInt(st.nextToken());
29+
}
5330

5431
int s = Integer.parseInt(br.readLine());
5532

56-
count = 1;
57-
58-
// 출발점부터 bfs 탐색 시작
5933
bfs(s - 1);
6034

61-
bw.write(String.valueOf(count));
35+
bw.write(String.valueOf(count + 1));
6236
bw.flush();
6337
bw.close();
6438
}
39+
40+
private static void bfs(int start) {
41+
Queue<Integer> queue = new LinkedList<>();
42+
queue.offer(start);
43+
visited[start] = true;
44+
45+
while (!queue.isEmpty()) {
46+
int cur = queue.poll();
47+
int right = cur + stones[cur];
48+
int left = cur - stones[cur];
49+
50+
if (right < n && !visited[right]) {
51+
visited[right] = true;
52+
queue.offer(right);
53+
count++;
54+
}
55+
56+
if (left >= 0 && !visited[left]) {
57+
visited[left] = true;
58+
queue.offer(left);
59+
count++;
60+
}
61+
}
62+
}
63+
6564
}

0 commit comments

Comments
 (0)