|
| 1 | +/** |
| 2 | + * 구현 |
| 3 | + * |
| 4 | + * 1. 사다리 정보와 뱀의 정보를 배열에 담기 |
| 5 | + * |
| 6 | + * 2. 1~100칸의 정보를 만들고 각 칸에 몇번만에 왔는지를 저장하면서 이동(방문했던 칸은 방문하지 않음) |
| 7 | + * |
| 8 | + * 3. 최종 100번째칸에 왔을때 몇번만에 왔는지 출력 |
| 9 | + * |
| 10 | + */ |
| 11 | + |
| 12 | +import java.util.*; |
| 13 | +import java.io.*; |
| 14 | + |
| 15 | + |
| 16 | +public class BJ16928_뱀과사다리게임 { |
| 17 | + |
| 18 | + public static int[] map = new int[101]; |
| 19 | + public static int[] cmap = new int[101]; |
| 20 | + public static void main(String[] args) throws IOException{ |
| 21 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 22 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 23 | + StringTokenizer st; |
| 24 | + |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + |
| 27 | + int ladder = Integer.parseInt(st.nextToken()); |
| 28 | + int snake = Integer.parseInt(st.nextToken()); |
| 29 | + |
| 30 | + // 사다리 정보 저장 |
| 31 | + for(int i = 0; i < ladder; i++){ |
| 32 | + st = new StringTokenizer(br.readLine()); |
| 33 | + |
| 34 | + int start = Integer.parseInt(st.nextToken()); |
| 35 | + int end = Integer.parseInt(st.nextToken()); |
| 36 | + |
| 37 | + map[start] = end; |
| 38 | + } |
| 39 | + |
| 40 | + // 뱀 정보 저장 |
| 41 | + for(int i = 0; i < snake; i++){ |
| 42 | + st = new StringTokenizer(br.readLine()); |
| 43 | + |
| 44 | + int start = Integer.parseInt(st.nextToken()); |
| 45 | + int end = Integer.parseInt(st.nextToken()); |
| 46 | + |
| 47 | + map[start] = end; |
| 48 | + } |
| 49 | + // 게임시작 |
| 50 | + check(); |
| 51 | + System.out.println(cmap[100]); |
| 52 | + } |
| 53 | + |
| 54 | + //게임 |
| 55 | + public static void check(){ |
| 56 | + Queue<Integer> q = new LinkedList<>(); |
| 57 | + |
| 58 | + q.offer(1); |
| 59 | + cmap[1] = 0; |
| 60 | + while(!q.isEmpty()){ |
| 61 | + |
| 62 | + int cur = q.poll(); |
| 63 | + |
| 64 | + if(cur == 100){ |
| 65 | + break; |
| 66 | + } |
| 67 | + // 주사위 굴리기 |
| 68 | + for(int i = 1; i <= 6; i++){ |
| 69 | + |
| 70 | + if(cur+i > 100) continue; |
| 71 | + |
| 72 | + // 이동할 곳이 사다리,뱀 없고 방문하지 않았던 곳 |
| 73 | + if(cmap[cur+i] == 0 && map[cur+i] == 0){ |
| 74 | + cmap[cur+i] = cmap[cur]+1; |
| 75 | + q.offer(cur+i); |
| 76 | + } |
| 77 | + // 사다리나 뱀이 있음 |
| 78 | + else if(map[cur+i] != 0){ |
| 79 | + // 사다리 뱀의 최종위치 |
| 80 | + int move = map[cur+i]; |
| 81 | + //최종위치 방문 안했던 곳이면 방문 |
| 82 | + if(cmap[move] == 0){ |
| 83 | + cmap[move] = cmap[cur]+1; |
| 84 | + q.offer(move); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments