Prime Path(宽搜)

#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int m, n, ans = 9999;
bool vst[10000] = { 0 }, su[10000] = {0};
struct node {
    int num;                                       //数
    int step;                                       //深度
}now,nex;
queue<node>q;

void sushushai() {                           //素数筛
    for (int i = 1000;i <= 9999;i++) {
        int work = 0;
        for (int j = 2;j <= sqrt(i);j++) {
            if (i % j == 0) { work = 1;break; }
        }
        if (work == 0)su[i] = 1;
    }
}

void bfs() {
    if (now.num == n) {
        cout << now.step << endl;
        return;
    }
    while (!q.empty()) {
        now = q.front();                           //now是要进行变化的数
        char t[5];
        t[1] = now.num / 1000;
        t[2] = now.num % 1000 / 100;
        t[3] = now.num % 100 / 10;
        t[4] = now.num % 10;
        for (int i = 1;i <= 4;i++) {
            int temp = t[i];                                                           //存一下本位
            for (int j = 0;j <= 9;j++) {
                if (i == 1 && j == 0)continue;                                //第一位不能为0
                t[i] = j;
                nex.num = t[1] * 1000 + t[2] * 100 + t[3] * 10 + t[4];
                nex.step = now.step + 1;
                if (su[nex.num] == 1 && vst[nex.num] == 0) {    //若符合条件则存入队列
                    if (nex.num == n) {                                          //达到目标则输出当前深度 return
                        cout << nex.step << endl;
                        return; 
                    }
                    vst[nex.num] = 1;                          //未达到目标则将其存入队列
                    q.push(nex);
                }
            }
            t[i] = temp;                                             //恢复本位
        }
        q.pop();                                                 //遍历完成弹出now
    }
}

int main() {
    sushushai();
    int k;
    cin >> k;
    while (k--) {
        //初始化
        memset(vst, 0, sizeof(vst));
        ans = 0;
        q = queue<node>();


        cin >> m >> n;
        now.num = m;
        now.step = 0;
        vst[m] = 1;
        q.push(now);
        bfs();
    }
}

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值