涉及算法:bfs
题目大意:将一个四位的素数a变成四位的素数b需要多少次改变?注意,每次只能改变某一位的数字,且改变后的数也是素数。
题目分析:40入口的bfs
代码如下:
题目大意:将一个四位的素数a变成四位的素数b需要多少次改变?注意,每次只能改变某一位的数字,且改变后的数也是素数。
题目分析:40入口的bfs
代码如下:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main_3126
{
static int a,b;
static Queue<Integer> q;
static int[] used;//used[i]=1:表示数i已经出现过了
static int[] step;//step[i]:变成i最少需要的步数
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n=in.nextInt();
while(n-->0)
{
q=new LinkedList<Integer>();
used=new int[10000];
step=new int[10000];
a=Integer.parseInt(in.next());
b=Integer.parseInt(in.next());
System.out.println(bfs());
}
}
static int bfs()
{
int head=0,next=0;
q.offer(a);
used[a]=1;
step[a]=0;
while(!q.isEmpty())
{
head=q.poll();
for(int i=1;i<=9;i+=2)//改变个位
{
next=(head/10)*10+i;
if(isPrime(next) && used[next]==0)
{
q.offer(next);
step[next]=step[head]+1;
used[next]=1;
if(next==b) return step[next];
}
}
for(int i=0;i<=9;i++)//十位
{
next=(head/100)*100+head%10+i*10;
if(isPrime(next) && used[next]==0)
{
q.offer(next);
step[next]=step[head]+1;
used[next]=1;
if(next==b) return step[next];
}
}
for(int i=0;i<=9;i++)//百位
{
next=(head/1000)*1000+head%100+i*100;
if(isPrime(next) && used[next]==0)
{
q.offer(next);
step[next]=step[head]+1;
used[next]=1;
if(next==b) return step[next];
}
}
for(int i=1;i<=9;i++)//千位
{
next=head%1000+i*1000;
if(isPrime(next) && used[next]==0)
{
q.offer(next);
step[next]=step[head]+1;
used[next]=1;
if(next==b) return step[next];
}
}
}
return -1;
}
static boolean isPrime(int d)//判断d是否为素数
{
for(int i=2;i<=Math.sqrt(d);i++)
{
if(d%i==0)
{
return false;
}
}
return true;
}
}