1. 程式人生 > 實用技巧 >Prime Path

Prime Path

Prime Path

Prime Path

和一般的bfs走迷宮差不多,要注意的就是提前先判斷素數,還有bfs的方向是4*10,兩個迴圈就可以了。

#include <iostream>
#include <set>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

int mod = 9973;
const int INF = 0x3f3f3f3f;
const int maxn = 1e4 + 10;

int num[maxn];
int vis[maxn];
int f(int x)
{
	for (int i = 2; i < x; i++)
		if (x % i == 0)
			return 0;
	return 1;
}
void solve()
{
	int i;
	for (i = 1000; i < 10000; i++)
	{
		if (f(i))
			num[i] = 1;
	}
}
struct node
{
	int x, cnt;
	node(int x, int cnt) : x(x), cnt(cnt) {}
};

int bfs(int a, int b)
{
	queue<node> q;
	vis[a] = 1;
	if (a == b)
		return 0;
	node t(a, 0), r(0, 0);
	q.push(t);
	while (!q.empty())
	{
		t = q.front(), q.pop();
		r.cnt = t.cnt + 1;
		int mult = 1;
		for (int k = 1; k <= 4; k++)
		{
			int tem = t.x % (mult * 10);
			tem /= mult;
			//cout << tem << '\n';
			for (int i = 0; i < 10; i++)
			{
				r.x = t.x - tem * mult;
				r.x += mult * i;
				if (r.x == b)
					return r.cnt;
				if (!vis[r.x] && num[r.x])
				{
					vis[r.x] = 1;
					q.push(r);
				}
			}
			mult *= 10;
		}
	}
	return -1;
}
int main()
{
	solve();
	int T;
	int a, b;
	cin >> T;
	while (T--)
	{
		memset(vis, 0, sizeof(vis));
		cin >> a >> b;
		int tem = bfs(a, b);
		if (tem == -1)
			cout << "Impossible" << endl;
		else
			cout << tem << endl;
	}
	return 0;
}