hdu 1067 广搜+map

广搜+map

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1067

原帖地址:http://hi.baidu.com/ehoifivrahbkqur/item/b88b17c90d3c4e2e46d5c0f9

#include <iostream>
#include <string>
#include <map>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
map<string,int>m;

struct re{
    int ll[4][8];
    int step;
};
void tostring(struct re a,char *str){
    int i,j,k;
    for(i=k=0;i<4;i++)
        for(j=1;j<8;j++){
            str[k++]=a.ll[i][j]/10+'a';
            str[k++]=a.ll[i][j]%10+'a';
        }
    str[k]='\0';
}
int change(struct re *a,int pox,int poy){
    int i,j;
    struct re tem=*a;
    if(poy==0||tem.ll[pox][poy-1]%10==7||tem.ll[pox][poy-1]==0)
        return 0;
    for(i=0;i<4;i++)
        for(j=0;j<8;j++){
            if(tem.ll[i][j]==tem.ll[pox][poy-1]+1){
                a->ll[pox][poy]=a->ll[i][j];
                a->ll[i][j]=0;
                return 1;
            }
        }
}

int ju(struct re a){
    int i,j;
    for(i=10;i<50;i+=10)
        for(j=1;j<8;j++)
            if(a.ll[i/10-1][j-1]!=i+j)
                return 0;
    return 1;
}

int judge(struct re a){
    char str[100];
    tostring(a,str);
    if(m[str]>0) return 1;
    m[str]=1;
    return 0;
}

int bfs(struct re a){
    int i,j,step;
    struct re tem,tem2;
    queue<struct re>q;
    a.step=0;
    q.push(a);
    m.clear();
    while(!q.empty()){
        tem=q.front();
        q.pop();
        step=tem.step;
        for(i=0;i<4;i++)
            for(j=0;j<8;j++){
                if(tem.ll[i][j]==0){
                    tem2=tem;
                    if(change(&tem2,i,j)==0)
                        continue;
                    if(ju(tem2)) return step+1;
                    if(judge(tem2)) continue;
                    tem2.step=step+1;
                    q.push(tem2);
                }
            }
    }
    return -1;
}

int main(void){
    int T,i,j;
    struct re a;
    string ss;
    map<string,int>m;
    scanf("%d",&T);
    while(T--){
        for(i=0;i<4;i++)
            for(j=1;j<8;j++){
                scanf("%d",&a.ll[i][j]);
                if(a.ll[i][j]%10==1)
                    a.ll[i][j]=0;
            }
        a.ll[0][0]=11;
        a.ll[1][0]=21;
        a.ll[2][0]=31;
        a.ll[3][0]=41;
        if(ju(a)){
            printf("0\n");
            continue;
        }
        printf("%d\n",bfs(a));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值