Question: Give You A 4-digit number and a 4-digit number. For example, if the previous number moves only one digit at a time, ask if you can change the first number to the second one.
Transfer Condition: 1. It can only be used as a transit number through a prime number. 2. One digit is moved at a time.
If the minimum number of transfer (or step) is found, the output impossible is not found.
Policy: for example, question.
Directly run the Code:
# Include <stdio. h> # include <string. h >#include <queue> # define M 10005 Using STD: queue; int vis [10000]; int prime [10005] = {1, 1 }; struct node {int V [5]; int step ;}; node St, en; queue <node> q; void F () // locate the prime number within 10000 {int I, j; for (I = 2; I <10005; I ++) {If (prime [I] = 0) {for (j = I + I; j <m; J + = I) {Prime [J] = 1 ;}}} int match (node S1, node S2) {int I; for (I = 0; I <4; I ++) {If (s1.v [I]! = S2.v [I]) return false;} return true;} int BFS () {memset (VIS, 0, sizeof (VIS); int I, j, ANS = 0x3f3f3f; q. push (ST); int temp = ST. V [0] * 1000 + st. V [1] * 100 + st. V [2] * 10 + st. V [3]; vis [temp] = 1; while (! Q. empty () {node u = Q. front (); If (MATCH (u, en) {ans = u. step; break;} for (I = 0; I <4; I ++) {J = 0; if (I = 0) {j = 1 ;}for (; j <= 9; j ++) {node v = u; V. V [I] = J; V. step = u. step + 1; temp = v. V [0] * 1000 + v. V [1] * 100 + v. V [2] * 10 + v. V [3];/* If (MATCH (v, en) {return v. step;} */If (! Vis [temp] & prime [temp] = 0) {vis [temp] = 1; // printf ("% d .. ", temp); q. push (v) ;}} Q. pop () ;}while (! Q. empty () Q. pop (); Return ans;} int main () {f (); char S1 [5], S2 [5]; int T, I, J; scanf ("% d", & T); While (t --) {scanf ("% S % s", S1, S2); for (I = 0; I <strlen (S1); I ++) {St. V [I] = S1 [I]-'0';} St. step = 0; for (I = 0; I <strlen (S2); I ++) {en. V [I] = S2 [I]-'0';} int ans = BFS (); If (ANS! = 0x3f3f3f3f) printf ("% d \ n", ANS); elseprintf ("impossible \ n ");}}
Question link: Click the open link