Question:
Give you two four-digit prime numbers s and t. Each time you change a number, the changed number is also a prime number, and find the minimum number of changes from s to t.
Ideas:
First, obtain all the four-digit prime numbers.
If there is only one difference between two prime numbers, a graph is created (bidirectional)
Finally, find the shortest path (SPFA or BFS)
# Include
# Include
# Include
# Define deusing namespace std; const int MAXN = 10000 + 10; const int INF = 0x3ffffff; bool isprimer [MAXN]; int primer [MAXN], num; int head [MAXN], len; struct edge {int to, next;} e [MAXN * 10]; void add (int from, int to) {e [len]. to = to; e [len]. next = head [from]; head [from] = len ++;} // judge whether two numbers have only one digit but different bool judge (char * x, char * y) {int cnt = 0; for (int I = 0; I <4; I ++) if (x [I] = y [I]) cnt ++; return cnt = 3;} int dis [MAXN]; bool vis [MAXN]; int spfa (int s, int t) {for (int I = 1000; I <= 10000; I ++) {dis [I] = INF; vis [I] = 0;} dis [s] = 0; vis [s] = true; queue
Q; q. push (s); while (! Q. empty () {int cur = q. front (); q. pop (); for (int I = head [cur]; I! =-1; I = e [I]. next) {int to = e [I]. to; if (dis [cur] + 1 <dis [to]) {dis [to] = dis [cur] + 1; if (! Vis [to]) q. push (to) ;}}return dis [t];} int main () {memset (head,-1, sizeof (head); num = len = 0; for (int I = 2; I * I