알고리즘
백준 14248번 점프 점프 (JAVA)
박카스마시며코딩
2022. 7. 25. 22:54
https://www.acmicpc.net/problem/14248
14248번: 점프 점프
첫 번째 줄에는 돌다리의 돌 개수 n이 주어진다.(1≤n≤100,000) 돌의 번호는 왼쪽부터 1번에서 n번이다. 다음 줄에는 그 위치에서 점프할 수 있는 거리 Ai가 주어진다.(1≤Ai≤100,000) 다음 줄에는 출
www.acmicpc.net
저는 해당 문제를 BFS를 이용해 문제를 해결하였습니다.
방문 체크를 하고 해당 노드에 방문한 적이 없으면 방문하면서 결과값을 늘렸습니다.
package BOJ.bfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_14248 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int[] input = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++){
input[i] = stoi.apply(st.nextToken());
}
int start = stoi.apply(br.readLine()) - 1;
int result = bfs(start,n,input);
System.out.println(result);
}
private static int bfs(int start, int n, int[] input) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[n];
q.offer(start);
visited[start] = true;
int result = 1;
while(!q.isEmpty()){
int now = q.poll();
for(int i = -1 ; i <= 1 ; i++){
if(i == 0){
continue;
}
int next = now + i * input[now];
if(checkBound(next,n) && !visited[next]){
result++;
visited[next] = true;
q.offer(next);
}
}
}
return result;
}
private static boolean checkBound(int now, int n){
if(now >= 0 && now < n){
return true;
}
return false;
}
}