样例输出 SampleOutput [复制数据]
4
注意判重的方法
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<string>
#include<queue>
#define MAX 1000003
#define Max 100003
using namespace std;
string goal = "123804765";
int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
struct node{
int x, y, z,step;
string num;
};
int c;
int key[MAX], head[MAX], Next[MAX];
node start;
int step,number;
void Init(){
memset(head, -1, sizeof(head));
memset(Next, 0, sizeof(Next));
}
int Hash(string &cont){
number = 0;
for (int i = 0; i<9; i++){
number =number*10+ cont[i]-'0';
}
return number%MAX;
}
void Add(string &cont){
int h = Hash(cont);
key[c] = number;
Next[c] = head[h];
head[h] = c;
c++;
}
int Find(string &cont){
int h = Hash(cont);
for (int i = head[h]; i != -1; i = Next[i]){
if (key[i] == number){
return 1;
}
}
return 0;
}
/*struct hashNode{
string num;
hashNode *next;
};
struct hashHead{
hashNode *head;
};
hashHead HashHead[MAX];
int Find(string &cont){
int h = Hash(cont);
hashNode *temp = HashHead[h].head;
while (temp){
if (temp->num == cont){
return 1;
}
temp = temp->next;
}
return 0;
}
int Build_Hash(string &cont){
int h = Hash(cont);
if (Find(cont))
return 0;
else {
hashNode *HashNode = new hashNode;
HashNode->next = HashHead[h].head;
HashNode->num = cont;
HashHead[h].head = HashNode;
return 1;
}
}*/
void bfs(){
queue<node>q;
q.push(start);
while (!q.empty()){
node temp = q.front();
q.pop();
if (temp.num == goal){
cout << temp.step << endl;
return ;
}
Add(temp.num);
for (int i = 0; i < 4; i++){
int nx = temp.x + dir[i][0];
int ny = temp.y + dir[i][1];
int nz = 3 * nx + ny;
string tp = temp.num;
if (nx >= 0 && ny >= 0 && nx < 3 && ny < 3){
char ch = tp[temp.z];
tp[temp.z] = tp[nz];
tp[nz] = ch;
if (!Find(tp)){
Add(tp);
node newnode;
newnode.num = tp, newnode.x = nx, newnode.y = ny;
newnode.z = nz; newnode.step = temp.step+1;
q.push(newnode);
}
}
}
}
}
int main(){
Init();
string s; cin >> s; start.num = s;
for (int i = 0; i < s.length(); i++){
if (s[i] == '0'){
start.x = i / 3, start.y = i % 3;
start.z = i;
}
}
bfs();
//system("pause");
}