|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static boolean[] isPrime = new boolean[10000]; |
| 7 | + |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + |
| 11 | + Arrays.fill(isPrime, true); |
| 12 | + isPrime[0] = isPrime[1] = false; |
| 13 | + for (int i = 2; i * i < 10000; i++) { |
| 14 | + if (isPrime[i]) { |
| 15 | + for (int j = i * i; j < 10000; j += i) isPrime[j] = false; |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + int T = Integer.parseInt(br.readLine()); |
| 20 | + for (int t = 0; t < T; t++) { |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + int start = Integer.parseInt(st.nextToken()); |
| 23 | + int end = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + int result = bfs(start, end); |
| 26 | + System.out.println(result == -1 ? "Impossible" : result); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + static int bfs(int start, int end) { |
| 31 | + Queue<Integer> q = new LinkedList<>(); |
| 32 | + int[] dist = new int[10000]; |
| 33 | + Arrays.fill(dist, -1); |
| 34 | + |
| 35 | + q.add(start); |
| 36 | + dist[start] = 0; |
| 37 | + |
| 38 | + while (!q.isEmpty()) { |
| 39 | + int curr = q.poll(); |
| 40 | + if (curr == end) return dist[curr]; |
| 41 | + |
| 42 | + for (int i = 0; i < 4; i++) { |
| 43 | + int[] digits = getDigits(curr); |
| 44 | + |
| 45 | + for (int d = 0; d <= 9; d++) { |
| 46 | + if (i == 3 && d == 0) continue; |
| 47 | + |
| 48 | + int next = changeDigit(digits, i, d); |
| 49 | + |
| 50 | + if (isPrime[next] && dist[next] == -1) { |
| 51 | + dist[next] = dist[curr] + 1; |
| 52 | + q.add(next); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return -1; |
| 58 | + } |
| 59 | + |
| 60 | + static int[] getDigits(int num) { |
| 61 | + int[] digits = new int[4]; |
| 62 | + for (int i = 0; i < 4; i++) { |
| 63 | + digits[i] = num % 10; |
| 64 | + num /= 10; |
| 65 | + } |
| 66 | + return digits; |
| 67 | + } |
| 68 | + |
| 69 | + static int changeDigit(int[] digits, int idx, int d) { |
| 70 | + int res = 0; |
| 71 | + int p = 1; |
| 72 | + for (int i = 0; i < 4; i++) { |
| 73 | + if (i == idx) res += d * p; |
| 74 | + else res += digits[i] * p; |
| 75 | + p *= 10; |
| 76 | + } |
| 77 | + return res; |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
0 commit comments