1、项目概述
3х3九宫棋盘,放置数码为1~8的8个棋子,棋盘中留有一个空格,空格周围的棋子可以移动到空格中,从而改变棋盘的布局。根据给定初始布局和目标布局,移动棋子从初始布局到达目标布局,求解移动步骤并输出。请设计算法,使用合适的搜索策略,在较少的空间和时间代价下找到最短路径。
2、项目设计
重要的算法设计:A搜索算法即带有估价函数的优先队列BFS。
3、实验结果
运行截图:
实验代码:#include
#include
#include ch, int a, int b) { char c = ch[a]; ch[a] = ch[b]; ch[b] = c; }
int bfsHash(int start, int zeroPos) {
char temp[10];
node tempN(start, 0, zeroPos);//创建一个节点
que.push(tempN);//压入优先级队列
mymap[start] = 1;//标记开始节点被访问过
while (!que.empty()) {
tempN = que.top();
que.pop();//弹出一个节点
sprintf(temp, “%09d”, tempN.num);
int pos = tempN.zeroPos, k;
for (int i = 0; i < 4; i++) {
if (changeId[pos][i] != -1) {
swap(temp, pos, changeId[pos][i]);
sscanf(temp, “%d”, &k);
if (k == des)return tempN.step + 1;
if (mymap.count(k) == 0) {
node tempM(k, tempN.step + 1, changeId[pos][i]);
que.push(tempM);//创建一个新节点并压入队列
mymap[k] = 1;
}
swap(temp, pos, changeId[pos][i]);
}
}
}
}
int main() {
int n, k, b;
scanf("%s", arr);
for (k = 0; k < 9; k++)
if (arr[k] == ‘0’)break;
sscanf(arr, “%d”, &n);
b = bfsHash(n, k);
printf("%d步即可变换完成", b);
return 0;
}