백준/그래프 이론
16928 뱀과 사다리 게임
have a good time
2024. 6. 18. 22:01
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int move[];
static boolean visit[];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
move = new int[100];
visit = new boolean[100];
for(int i=0; i<N+M; i++) {
st = new StringTokenizer(br.readLine(), " ");
int a= Integer.parseInt(st.nextToken());
int b= Integer.parseInt(st.nextToken());
move[a] = b;
}
int result = solve(1);
System.out.println(result);
}
public static int solve(int start) {
Queue<Integer> q = new LinkedList<>();
q.add(start);
int count = 0;
solve2:
while(!q.isEmpty()) {
count++; // 현재 깊이(레벨)에서 주사위를 굴린 횟수를 증가
int size = q.size();
// 큐 크기(size) 만큼 for문 돌려야
// while문 내에서 count변수를 사용해서 답을 출력함.
for(int i= 0; i<size; i++ ) {
int now = q.poll();
for(int j=0; j<=6; j++) {
int next = now+j;
if(next>100) {
continue;
}if(next==100) {
break solve2;
}
// visit 사용 이유
// -> 똑같은 위치로 다시 이동하면 또 똑같이 경우의 수 찾을거라..
// -> visit 사용 안 하면 메모리 초과 나옴.
if(visit[next]) {
continue;
}
// 뱀, 사다리
if(move[next]!=0) {
next = move[next];
}
visit[next] = true;
q.add(next);
}
}
}
return count;
}
}