|
| 1 | +//BOJ13549 숨바꼭질3, 골드5 |
| 2 | +//기존 숨바꼭질 문제에서 최단경로 기능이 추가됨 |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class BOJ13549 { |
| 7 | + static class Node{ |
| 8 | + int idx; |
| 9 | + int time; |
| 10 | + public Node(int idx, int time) { |
| 11 | + this.idx = idx; |
| 12 | + this.time = time; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + static int[] point; |
| 17 | + static int N, K, ans; |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 20 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + |
| 23 | + N = Integer.parseInt(st.nextToken()); |
| 24 | + K = Integer.parseInt(st.nextToken()); |
| 25 | + point = new int[100000+1]; |
| 26 | + ans = bfs(); |
| 27 | + |
| 28 | + bw.write(ans + "\n"); |
| 29 | + bw.flush(); |
| 30 | + bw.close(); |
| 31 | + br.close(); |
| 32 | + } |
| 33 | + static int bfs() { |
| 34 | + if(N == K) return 0; // 0, 0일 때 예외 케이스 처리해줘야한다. |
| 35 | + |
| 36 | + Queue<Node> q = new LinkedList<>(); |
| 37 | + // 시작 time을 1로 해놓고, 결과 출력시 1 빼기. point의 값이 0인 것(방문 안한 곳)과 구별해주기 위해서. |
| 38 | + q.add(new Node(N, 1)); |
| 39 | + point[N] = 1; |
| 40 | + |
| 41 | + while(!q.isEmpty()) { |
| 42 | + Node cur = q.poll(); |
| 43 | + |
| 44 | + if(cur.idx + 1 >= 0 && cur.idx+1 <= 100000) { //앞으로 한칸 |
| 45 | + if(point[cur.idx+1] == 0 || point[cur.idx+1] > cur.time+1) { |
| 46 | + point[cur.idx+1] = cur.time + 1; |
| 47 | + q.add(new Node(cur.idx + 1, cur.time+1)); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if(cur.idx - 1 >= 0 && cur.idx-1 <= 100000) { //뒤로 한칸 |
| 52 | + if(point[cur.idx-1] == 0 || point[cur.idx-1] > cur.time+1) { |
| 53 | + point[cur.idx-1] = cur.time + 1; |
| 54 | + q.add(new Node(cur.idx - 1, cur.time+1)); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + if(cur.idx * 2 >= 0 && cur.idx*2 <= 100000) { //순간이동 |
| 59 | + if(point[cur.idx*2] == 0 || point[cur.idx*2] > cur.time) { |
| 60 | + point[cur.idx*2] = cur.time; |
| 61 | + q.add(new Node(cur.idx * 2, cur.time)); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + } |
| 67 | + if(point[K] != 0) return point[K] - 1; |
| 68 | + return -1; |
| 69 | + } |
| 70 | +} |
0 commit comments