#include<bits/stdc++.h>
using namespace std;
typedef int State[9];
const int maxstate = 1e6;
State st[maxstate], goal;
int dist[maxstate];
const int dx[4] = { -1,1,0,0 };//用来控制x坐标的移动
const int dy[4] = { 0,0,-1,1 };//用来控制y坐标的移动
const int hashsize = 1e6 + 3;用来取模
int head[hashsize], nxt[maxstate];//head和nxt数组是用来构建哈希链表
int hashs(State& s)//构建哈希表
{
int v = 0;
for (int i = 0; i < 9; i++) v = v * 10 + s[i];
return v % hashsize;
}
int try_to_insert(int s)
{
int h = hashs(st[s]);
int u = head[h];
while (u)
{
if (memcmp(st[u], st[s], sizeof(st[s])) == 0) return 0;
u = nxt[u];
}
nxt[s] = head[h];//可以看出这里使用的是链表法来解决冲突
head[h] = s;
return 1;
}
int bfs()
{
int front = 1, rear = 2;
while (front < rear)
{
State&s = st[front];//这里的“&”不是取地址,在c++中表示引用,有点类似于指针的感觉,就是如果你对s进行修改,那么相对应的st【】的那个也会修改;
if (memcmp(goal, s, sizeof(s)) == 0) return front;
int z;
for (z = 0; z < 9; z++) if (!s[z]) break;
int x = z / 3, y = z % 3;
for (int d = 0; d < 4; d++)
{
int newx = x + dx[d], newy = y + dy[d];
int newz = newx * 3 + newy;
if (newx < 0 || newx >= 3 || newy < 0 || newy >= 3) continue;
State& t = st[rear];
memcpy(&t, &s, sizeof(s));
t[newz] = s[z];
t[z] = s[newz];
dist[rear] = dist[front] + 1;
if (try_to_insert(rear)) rear++;
}
front++;
}
return 0;
}
int main()
{
for (int i = 0; i < 9; i++) scanf("%d", &st[1][i]);//输入初始状态的八数码图
for (int i = 0; i < 9; i++) scanf("%d", &goal[i]);//输入你想要的终态八数码图
int ans = bfs();//进行bfs搜索
if (ans > 0) printf("%d", dist[ans]);
return 0;
}
关于八数码,详见http://acm.hdu.edu.cn/showproblem.php?pid=1043
关于这道题,我也写了博客https://blog.csdn.net/qq_41670466/article/details/84316948里面使用康托展开,大家可以自己百度一下。