数字可输入
时间: 2023-11-18 20:05:18 浏览: 34
好的,下面是带数字输入的八数码问题的 C++ 代码:
```c++
#include <bits/stdc++.h>
using namespace std;
const int N = 3; // 8数码问题的规模为3
const int dx[] = {0, 0, 1, -1}; // 四个方向的x坐标变化
const int dy[] = {1, -1, 0, 0}; // 四个方向的y坐标变化
struct Node {
int state[N][N]; // 当前状态
int x, y; // 空格的位置
int step; // 当前步数
Node() {}
Node(int s[][N], int _x, int _y, int _step) {
memcpy(state, s, sizeof(state));
x = _x, y = _y, step = _step;
}
};
int st[N][N]; // 初始状态
int ed[N][N]; // 目标状态
int bfs() {
queue<Node> q;
unordered_set<string> vis; // 判重
q.push(Node(st, 0, 0, 0));
vis.insert(string((char*)st, (char*)st + N * N)); // 将初始状态加入到visit中
while (q.size()) {
auto t = q.front();
q.pop();
if (!memcmp(t.state, ed, sizeof(ed))) return t.step; // 判断是否到达目标状态
for (int i = 0; i < 4; i ++ ) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 0 || a >= N || b < 0 || b >= N) continue; // 判断是否越界
auto c = t.state;
swap(c[t.x][t.y], c[a][b]); // 交换空格和相邻位置的数
if (vis.count(string((char*)c, (char*)c + N * N))) continue; // 判断是否重复
q.push(Node(c, a, b, t.step + 1)); // 将新状态加入队列
vis.insert(string((char*)c, (char*)c + N * N)); // 将新状态加入到visit中
}
}
return -1;
}
int main() {
cout << "请输入初始状态:" << endl;
for (int i = 0; i < N; i ++ )
for (int j = 0; j < N; j ++ )
cin >> st[i][j];
cout << "请输入目标状态:" << endl;
for (int i = 0; i < N; i ++ )
for (int j = 0; j < N; j ++ )
cin >> ed[i][j];
cout << bfs() << endl;
return 0;
}
```
在该代码中,我们在 `main` 函数中先输出提示信息,让用户输入初始状态和目标状态。在输入过程中,我们使用两个嵌套循环来读入每个数字。在 `bfs` 函数中,我们在搜索过程中,每次将新状态加入到哈希表中进行判重。