|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static class State { |
| 7 | + int num; |
| 8 | + String commands; |
| 9 | + |
| 10 | + State(int num, String commands) { |
| 11 | + this.num = num; |
| 12 | + this.commands = commands; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 18 | + int T = Integer.parseInt(br.readLine()); |
| 19 | + |
| 20 | + for (int i = 0; i < T; i++) { |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + int from = Integer.parseInt(st.nextToken()); |
| 23 | + int to = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + String result = bfs(from, to); |
| 26 | + System.out.println(result); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + private static String bfs(int from, int to) { |
| 31 | + Queue<State> queue = new LinkedList<>(); |
| 32 | + boolean[] visited = new boolean[10000]; |
| 33 | + |
| 34 | + queue.offer(new State(from, "")); |
| 35 | + visited[from] = true; |
| 36 | + |
| 37 | + while (!queue.isEmpty()) { |
| 38 | + State current = queue.poll(); |
| 39 | + |
| 40 | + if (current.num == to) { |
| 41 | + return current.commands; |
| 42 | + } |
| 43 | + |
| 44 | + int D = (current.num * 2) % 10000; |
| 45 | + if (!visited[D]) { |
| 46 | + visited[D] = true; |
| 47 | + queue.offer(new State(D, current.commands + "D")); |
| 48 | + } |
| 49 | + |
| 50 | + int S = current.num == 0 ? 9999 : current.num - 1; |
| 51 | + if (!visited[S]) { |
| 52 | + visited[S] = true; |
| 53 | + queue.offer(new State(S, current.commands + "S")); |
| 54 | + } |
| 55 | + |
| 56 | + int L = (current.num % 1000) * 10 + current.num / 1000; |
| 57 | + if (!visited[L]) { |
| 58 | + visited[L] = true; |
| 59 | + queue.offer(new State(L, current.commands + "L")); |
| 60 | + } |
| 61 | + |
| 62 | + int R = (current.num % 10) * 1000 + current.num / 10; |
| 63 | + if (!visited[R]) { |
| 64 | + visited[R] = true; |
| 65 | + queue.offer(new State(R, current.commands + "R")); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return ""; |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments