题目链接:POJ 3126
题意:每一组测试数据给定2个4位数的素数(第一位不为0),如1033,8179,要求每次只能变化一位,求从1033变化到8179需要多少步?这种情况的方案如下,需要6步
1033
1733
3733
3739
3779
8779
8179
Input
One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).
Output
One line for each case, either with a number stating the minimal cost or containing the word Impossible.
Sample Input
3
1033 8179
1373 8017
1033 1033
Sample Output
6
7
0
思路: 假设输入两个4位的素数分别为start,end。每次只能改变一位,搜索从start到end的路径。首先可以想象以起始数start为根节点(设根节点所在树的高度为0),所有树高为1的子节点为根节点变化1位后的所有可能的素数,以此类推,每个节点都是素数并且是由其父节点变化一位得到(但是不能重复,如一个素数在第1层出现,此后都不再出现)。
上面的搜索问题要求最短的路径,按层次遍历这颗树(用到BFS),如果有一条从根start到end节点的路径,则访问到end节点时结束遍历,end节点所在的高度就是从start到end的路径长度,从根节点到end节点路径上的节点就是每次变化过程的数。
代码
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <cstdio>
using namespace std;
const int N = 10010;
bool prime[N];//如果i是素数那么prime[i]为true
int steps[N];//steps[i]存储从start到i的步数
bool visited[N];//如果i被访问过,则visited[i]为true
void filter_prime() {
//筛法求素数
for (int i = 0; i < N; i++) prime[i] =</