hdu 1195 Open the Lock(广搜,简单)

题目

猜密码,问最少操作多少次猜对,思路很简单的广搜,各种可能一个个列出来就可以了,可惜我写的很搓。

不过还是很开心,今天第一个一次过了的代码

#define  _CRT_SECURE_NO_WARNINGS
//这是非一般的最短路,所以广搜到的最短的路不一定是所要的路线
//所以应该把所有的路径都搜索出来,找到最短的转折数,看他是不是不大于2
//我是 用边搜索边更新当前路径的最小转弯数 来写的
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
using namespace std;
bool vis[10000];
int a,b;

struct tt
{
    int x,step;
};

tt front,rear,temp;
queue<tt>q;

void solve(int x,int mark)
{
    int x1,x2,x3,x4;

    x1=temp.x/1000;
    x2=temp.x/100-x1*10;
    x3=temp.x/10-x1*100-x2*10;
    x4=temp.x%10;
    if(mark==0)
    {
        if(x==1)
            rear.x=x1*100+x2*1000+x3*10+x4;
        else if(x==2)
            rear.x=x1*1000+x2*10+x3*100+x4;
        else
            rear.x=x1*1000+x2*100+x3+x4*10;
    }
    else
    {
        if(x==1){
            x1+=mark;
            if(x1>9)x1-=9;
            else if(x1<1)x1+=9;
        }
        else if(x==2){
            x2+=mark;
            if(x2>9)x2-=9;
            else if(x2<1)x2+=9;
        }
        else if(x==3){
            x3+=mark;
            if(x3>9)x3-=9;
            else if(x3<1)x3+=9;
        }
        else {
            x4+=mark;
            if(x4>9)x4-=9;
            else if(x4<1)x4+=9;
        }
        rear.x=x1*1000+x2*100+x3*10+x4;
    }
    if(!vis[rear.x])
    {
        rear.step=temp.step+1;
        q.push(rear);
        vis[rear.x]=true;
    }
}
int bfs()
{
    
    while(!q.empty())
        q.pop();
    memset(vis,false,sizeof(vis));
    front.x=a;front.step=0;
    q.push(front);
    vis[a]=true;
    while(!q.empty())
    {
        temp=q.front();
        if(temp.x==b)
            return temp.step;
        q.pop();
        solve(1,1);
        solve(1,-1);
        solve(2,1);
        solve(2,-1);
        solve(3,1);
        solve(3,-1);
        solve(4,1);
        solve(4,-1);
        solve(1,0);
        solve(2,0);
        solve(3,0);
    }
    return 0;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&a,&b);
        printf("%d
",bfs());
    }
    return 0;
}
View Code
一道又一道,好高兴!
原文地址:https://www.cnblogs.com/laiba2004/p/3548717.html