#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)http://codeup.hustoj.com/problem.php?cid=100000609&pid=2#codeup一直无法AC,最后发现是输入的问题。