素数查找问题,而且只在4位数中查找只有一位不同的数。
思路,1.先将1000到9999的所有素数打表
2.在打表数组其中寻找一个与前一个只有一个数字之差的数
3 .找出的数进入队列,最基础的BFS解决
#include <iostream>
#include <math.h>
#include <queue>
#include <string.h>
#include <stdio.h>
using namespace std;
struct node{
int step;
int num;
};
int n, ans = 0;
int a[10000],book[10000];
void init(){
for(int i=1000;i<=9999;i++){
int z = sqrt(i);
int flag = 1;
for(int k=2;k<=z;k++){
if(i%k==0){
flag = 0;
}
}
if(flag) a[ans++]=i;
}
}
bool check(int q,int p){
int q1 = q/1000;
int q2 = q/100%10;
int q3 = q/10%10;
int q4 = q%10;
int p1 = p/1000;
int p2 = p/100%10;
int p3 = p/10%10;
int p4 = p%10;
int count = 0;
if( q1 != p1 ) count++;
if( q2 != p2 ) count++;
if( q3 != p3 ) count++;
if( q4 != p4 ) count++;
if( count == 1 ) return 1;
else return 0;
}
void bfs( int x, int y ) {
queue<node> qq;
node q;
q.step = 0;
q.num = x;
memset(book,0,sizeof(book));
book[x] = 1;
// cout<<" x = "<<x<<endl;
qq.push( q );
while(!qq.empty()){
node temp = qq.front();
qq.pop();
if(temp.num==y){
cout<<temp.step<<endl;
return;
}
for(int i=0;i<ans;i++){
int cn = a[i];
int tn = temp.num;
if(book[cn] == 0 ) {
if(check(cn,tn)){
book[cn]=1;
node tt ;
tt.step = temp.step+1;
tt.num = cn;
qq.push(tt);
}
}
}
}
return;
}
int main() {
cin>>n;
init();
int a, b;
for(int i = 1; i <= n; i++ ) {
cin>>a>>b;
bfs(a,b);
}
return 0;
}