https://www.acmicpc.net/problem/14248
1. 아이디어
BFS와 DFS 알고리즘을 활용하면 간단하게 해결할 수 있다.
2. 문제풀이
시작 위치에서 왼쪽 또는 오른쪽으로 점프를 하고 다시 이동한 위치에서 왼쪽 또는 오른쪽으로 이동하는 것을 반복하는 문제로 점프할 위치가 방문 가능한 위치인지만 체크하는 BFS, DFS로 구현했다.
3. 코드
import java.io.*;
import java.util.*;
public class Main_BFS {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
int[] jump = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
jump[i] = Integer.parseInt(st.nextToken());
}
int S = Integer.parseInt(br.readLine()) - 1;
int cnt = bfs(S, N, jump);
System.out.println(cnt);
}
private static int bfs(int start, int N, int[] jump) {
Queue<Integer> q = new ArrayDeque<>();
q.add(start);
boolean[] visited = new boolean[N];
visited[start] = true;
int cnt = 1;
while (!q.isEmpty()) {
int node = q.remove();
int jumpLeft = node - jump[node];
if (jumpLeft >= 0 && !visited[jumpLeft]) {
q.add(jumpLeft);
visited[jumpLeft] = true;
cnt++;
}
int jumpRight = node + jump[node];
if (jumpRight < N && !visited[jumpRight]) {
q.add(jumpRight);
visited[jumpRight] = true;
cnt++;
}
}
return cnt;
}
}
import java.io.*;
import java.util.*;
public class Main_DFS {
private static int N;
private static int[] jump;
private static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
jump = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
jump[i] = Integer.parseInt(st.nextToken());
}
visited = new boolean[N];
int S = Integer.parseInt(br.readLine()) - 1;
int cnt = dfs(S);
System.out.println(cnt);
}
private static int dfs(int node) {
visited[node] = true;
int cnt = 1;
int jumpLeft = node - jump[node];
if (jumpLeft >= 0 && !visited[jumpLeft]) {
cnt += dfs(jumpLeft);
}
int jumpRight = node + jump[node];
if (jumpRight < N && !visited[jumpRight]) {
cnt += dfs(jumpRight);
}
return cnt;
}
}
4. 후기
- BFS
- DFS
'코딩테스트 준비 > 백준' 카테고리의 다른 글
[백준] 5619번 - 세 번째 [Java] (0) | 2025.02.04 |
---|---|
[백준] 1094번 - 막대기 [Java] (0) | 2025.02.04 |
[백준] 1068번 - 트리 [Java] (0) | 2025.02.04 |
[백준] 1497번 - 기타콘서트 [Java] (0) | 2025.02.04 |
[백준] 16504번 - 종이접기 [Java] (0) | 2025.02.04 |