1. 程式人生 > >F - Prime Path ~~ [kuangbin帶你飛]專題一 簡單搜尋

F - Prime Path ~~ [kuangbin帶你飛]專題一 簡單搜尋

給你兩個四位的素數a,b。
a可以改變某一位上的數字變成c,但只有當c也是四位的素數時才能進行這種改變。
請你計算a最少經過多少次上述變換才能變成b。
例如:1033 -> 8179
1033
1733
3733
3739
3779
8779
8179
最少變換了6次。

Input

第一行輸入整數T,表示樣例數。 (T <= 100)
每個樣例輸入兩個四位的素數a,b。(沒有前導零)

Output

對於每個樣例,輸出最少變換次數,如果無法變換成b則輸出"Impossible"。

Sample Input

3
1033 8179
1373 8017
1033 1033

Sample Output

6
7
0

思路 : 這個題我寫的麻煩了,但是我這個思路好理解,單個字元輸入;

更改個位十位百位千位 進行搜尋

程式碼很好理解;

看程式碼就可以;

AC程式碼

#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
#include<string>
#include<stack>
#define ll long long
using namespace std;
int p(int x)
{
	if(x<2)
	{
		return 0;
	}
	for(int i=2 ; i*i<=x ; i++)
	{
		if(x%i==0)
		{
			return 0;
		}
		
	}
	return 1; 
} 
int x,y,z,w,e1,e2,e3,e4;
int book[10][10][10][10];
struct Node
{
	int x,y,z,w,s;
	Node(){}
	Node(int xx,int yy,int zz,int ww,int ss) : x(xx) , y(yy) , z(zz) , w(ww) , s(ss) {} 
};
int bfs(int x,int y,int z,int w,int s)
{
	memset(book,0,sizeof(book));
	book[x][y][z][w] = 1 ;
	queue<Node> Q;           
	Q.push(Node(x,y,z,w,s));
	while(!Q.empty())
	{
		Node u = Q.front() ;
		Q.pop() ;
		if(u.x == e1 && u.y == e2 && u.z == e3 && u.w==e4)
		{
		//	cout<<u.x<<u.y<<u.z<<u.w<<endl;
			return u.s ;
		}
 
 
		for(int j = 1 ; j<=9 ; j++)   //千位 
		{
			int xx = j ;
			int data = xx * 1000 + u.y * 100 + u.z * 10 + u.w ;
			if(p(data)==1 && book[xx][u.y][u.z][u.w] == 0)
			{
				book[xx][u.y][u.z][u.w] = 1 ;
			//	cout<<xx<<u.y<<u.z<<u.w<<endl;
				int ss=u.s+1;
				Q.push(Node(xx,u.y,u.z,u.w,ss));
			}
		}
	

		for(int j = 0 ; j<=9 ; j++)  // 百位 
		{
			int yy = j ;
			int data = u.x * 1000 + yy * 100 + u.z * 10 + u.w ;
			if(p(data)==1 && book[u.x][yy][u.z][u.w] == 0)
			{
				book[u.x][yy][u.z][u.w] = 1 ;
		//		cout<<u.x<<yy<<u.z<<u.w<<endl;
				int ss=u.s+1;
				Q.push(Node(u.x,yy,u.z,u.w,ss));
			}
		}
	

		for(int j = 0 ; j<=9 ; j++)  //十 
		{
			int zz = j ;
			int data = u.x * 1000 + u.y * 100 + zz * 10 + u.w ;
			if(p(data)==1 && book[u.x][u.y][zz][u.w] == 0)
			{
				book[u.x][u.y][zz][u.w] = 1 ;
				int ss=u.s+1;
		//		cout<<u.x<<u.y<<zz<<u.w<<endl;
				Q.push(Node(u.x,u.y,zz,u.w,ss));
			}
		}
	

		for(int j = 0 ; j<=9 ; j++)  //個 
		{
			int ww = j ;
			int data = u.x * 1000 + u.y * 100 + u.z * 10 + ww ;
			if(p(data)==1 && book[u.x][u.y][u.z][ww] == 0)
			{
				book[u.x][u.y][u.z][ww] = 1 ;
				int ss=u.s+1;
		//		cout<<u.x<<u.y<<u.z<<ww<<endl;
				Q.push(Node(u.x,u.y,u.z,ww,ss));
			}
		}
			
		
	}
	return -1;
	
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		char a;
		cin>>a;
		x=a-'0';
		cin>>a;
		y=a-'0';
		cin>>a;
		z=a-'0'; 
		cin>>a;
		w=a-'0';
		getchar();
		cin>>a;
		e1=a-'0';
		cin>>a;
		e2=a-'0'; 
		cin>>a;
		e3=a-'0';
		cin>>a;
		e4=a-'0';
		int ans = bfs(x,y,z,w,0) ;
		if(ans == -1)
		{
			cout<<"Impossible"<<endl;
		 } 
		 else
		 {
		 	cout<<ans<<endl;
		 }
	}
	

}