【宽搜入门】8数码难题

#include<cstdio>
#include<unordered_map>
#include<queue>
#include<algorithm>
#include<string>
using namespace std;
string endstr;
queue<string>q;
unordered_map<string, int>map;
int x[] = {0,0,1,-1};
int y[] = {-1,1,0,0};
bool judge(int x, int y){
    if(x<0||x>=3 ||y<0||y>=3)
        return false;
    return true;
}
int bfs(string str){
    map[str]=1;
    q.push(str); // 压入状态
    string tmp;
    while(!q.empty()){
        tmp = q.front(); //获取第一个元素
        q.pop();
        int step = map[tmp];
        if(tmp==endstr){
            return step;
        }
        // 获取0的位置
        int n = tmp.find("0"); //""输出子串第一次出现的位置
        int pos_x = n/3;int pos_y = n%3;
        for(int i=0;i<4;i++){ // 探照灯往4个方向照
            int new_x = pos_x + x[i];
            int new_y = pos_y + y[i];
            if(!judge(new_x, new_y)) //越界
                continue;
            // 交换
            swap(tmp[n], tmp[new_x*3+new_y]);
            if(map.find(tmp)==map.end()){//不存在该状态
                map[tmp]=step+1;
                q.push(tmp);
            }
            swap(tmp[n], tmp[new_x*3+new_y]); //恢复原样,继续探照
        }
    }
    return -1;
}
int main(){
   /* char s[10];char e[10];
    for(int i=0;i<9;i++){
        scanf("%c", &s[i]);
        getchar();
    }
    s[9]='\0'; 
    for(int i=0;i<9;i++){
        scanf("%c", &e[i]);
        getchar();
    }
    e[9]='\0';*/
    
    char s[10];char e[10];
    int termination=0;int n;
	for(int i=0;i<9;i++)
    {
        scanf("%d",&n);
        termination=termination*10+n;
    }
	sprintf(s,"%09d",termination);
    termination=0;
	for(int i=0;i<9;i++)
    {
        scanf("%d",&n);
        termination=termination*10+n;
    }
	sprintf(e,"%09d",termination);
    string str = s;
    endstr = e;
    printf("%d\n", bfs(str));   
}

问题 C: 【宽搜入门】8数码难题 - Codeup新家 (hustoj.com)icon-default.png?t=N7T8http://codeup.hustoj.com/problem.php?cid=100000609&pid=2#codeup一直无法AC,最后发现是输入的问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值