https://www.acmicpc.net/problem/17204
package BOJ.simulation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_17204 {
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 m = stoi.apply(st.nextToken());
int[] input = new int[n];
for(int i = 0 ; i < n ; i++){
input[i] = stoi.apply(br.readLine());
}
int result = bfs(input,n,m);
System.out.println(result);
}
private static int bfs(int[] input, int n, int m) {
int result = -1;
boolean[] visited = new boolean[n];
int now = 0;
int cnt = 0;
while(true){
cnt++;
int next = input[now];
if(next == m){
result = cnt;
break;
}
if(!visited[next]){
visited[next] = true;
now = next;
}else{
break;
}
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 17266번 어두운 굴다리 (JAVA) (0) | 2023.02.24 |
---|---|
백준 21317번 징검다리 건너기 (JAVA) (0) | 2023.02.23 |
백준 5212번 지구 온난화 (JAVA) (0) | 2023.02.21 |
백준 1197번 최소 스패닝 트리 (JAVA) (0) | 2023.02.20 |
프로그래머스 숫자 변환하기 (JAVA) (0) | 2023.02.19 |