#include <bits/stdc++.h>
using namespace std;
const int LEN = 362880; // 9! = 362880,总共可能的状态数
struct node {
int state[9]; // 存储8拼图的一个排列
int dis; // 到初始状态的距离
string path; // 到达此状态的路径
};
// 左、上、右、下移动方向
int dir[4][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };
char dirChar[4] = { 'l', 'u', 'r', 'd' };
// 访问数组,用于标记访问过的状态
int visited[LEN] = { 0 };
// 初始和目标状态
int start[9], goal[9];
// 阶乘数组,用于康托展开编码状态
long int factorial[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
// 康托展开,用于唯一编码状态
bool Cantor(int str[], int n, long& result) {
result = 0;
for (int i = 0; i < n; i++) {
int counted = 0;
for (int j = i + 1; j < n; j++) {
if (str[i] > str[j]) ++counted;
}
result += counted * factorial[n - i - 1];
}
if (!visited[result]) {
visited[result] = 1;
return true;
}
else {
return false;
}
}
// 广度优先搜索,寻找最短路径
string bfs() {
node head;
memcpy(head.state, start, sizeof(head.state));
head.dis = 0;
head.path = "";
queue<node> q;
long initialState;
Cantor(head.state, 9, initialState); // 编码初始状态
q.push(head);
while (!q.empty()) {
head = q.front();
q.pop();
if (memcmp(head.state, goal, sizeof(goal)) == 0) {
return head.path; // 找到目标状态
}
int z;
for (z = 0; z < 9; z++) {
if (head.state[z] == 0) break; // 找到0(空白块)的位置
}
int x = z / 3, y = z % 3; // 将1D索引转换为2D坐标
for (int i = 0; i < 4; i++) {
int newx = x + dir[i][0];
int newy = y + dir[i][1];
int nz = newx * 3 + newy; // 将2D坐标转换回1D索引
if (newx >= 0 && newx < 3 && newy >= 0 && newy < 3) { // 检查边界
node newnode;
memcpy(&newnode, &head, sizeof(node));
swap(newnode.state[z], newnode.state[nz]); // 移动空白块
newnode.dis++;
newnode.path += dirChar[i]; // 记录路径
long newState;
if (Cantor(newnode.state, 9, newState)) {
q.push(newnode); // 如果新状态未访问过,加入队列
}
}
}
}
return "unsolvable"; // 如果找不到解决方案
}
int main() {
// 读取初始和目标状态
char input;
for (int i = 0; i < 9; i++) {
cin >> input;
start[i] = (input == 'x') ? 0 : input - '0';
}
for (int i = 0; i < 9; i++) {
cin >> input;
goal[i] = (input == 'x') ? 0 : input - '0';
}
string result = bfs();
cout << result << endl;
return 0;
}
一道经典的八码图问题 使用bfs+康托哈希函数
大致原理为:
构建node数据结构储存每一种图的状态 利用route来记录路径
bfs遍历每一种情况类似于迷宫 利用康托哈希函数去除已找到状态 降低时间复杂度
当找到对应状态返回
新学习的函数:
memset(目标,原始,长度sizeof)
memcmp(目标,原始,长度sizeof)
memcpy(目标,原始,长度sizeof)