应用宽度优先搜索求解重排九宫问题,要求使用C++
时间: 2023-06-24 15:08:59 浏览: 49
好的,下面是一份使用C++实现宽度优先搜索求解重排九宫问题的代码,具体注释在代码中:
```cpp
#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct State {
int board[3][3]; // 保存当前状态的棋盘
int spaceX, spaceY; // 空格的位置
int depth; // 当前状态的深度
int heuristic; // 当前状态的启发值
string history; // 保存到达当前状态的操作序列
bool operator<(const State& other) const {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] != other.board[i][j]) {
return board[i][j] < other.board[i][j];
}
}
}
return false;
}
};
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int getHeuristic(State& state) {
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state.board[i][j] == 0) {
continue;
}
int x = (state.board[i][j] - 1) / 3;
int y = (state.board[i][j] - 1) % 3;
sum += abs(x - i) + abs(y - j);
}
}
return sum;
}
bool isSolved(State& state) {
int value = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state.board[i][j] != value) {
return false;
}
value++;
}
}
return true;
}
void printBoard(State& state) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << state.board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
int main() {
State initial;
// 初始化初始状态
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> initial.board[i][j];
if (initial.board[i][j] == 0) {
initial.spaceX = i;
initial.spaceY = j;
}
}
}
initial.depth = 0;
initial.heuristic = getHeuristic(initial);
initial.history = "";
queue<State> q;
map<State, bool> visited;
q.push(initial);
visited[initial] = true;
while (!q.empty()) {
State current = q.front();
q.pop();
if (isSolved(current)) {
cout << current.history << endl;
break;
}
for (int i = 0; i < 4; i++) {
int nx = current.spaceX + dx[i];
int ny = current.spaceY + dy[i];
if (nx < 0 || nx >= 3 || ny < 0 || ny >= 3) {
continue;
}
State next = current;
// 移动空格
swap(next.board[current.spaceX][current.spaceY], next.board[nx][ny]);
next.spaceX = nx;
next.spaceY = ny;
next.depth++;
next.heuristic = getHeuristic(next);
next.history += char('0' + i);
if (!visited[next]) {
q.push(next);
visited[next] = true;
}
}
}
return 0;
}
```
其中,State结构体表示状态,包括当前的棋盘、空格的位置、当前状态的深度、当前状态的启发值和到达当前状态的操作序列。isSolved函数判断当前状态是否为目标状态,getHeuristic函数计算当前状态的启发值,printBoard函数用于打印棋盘。在主函数中,使用宽度优先搜索求解重排九宫问题,每次移动空格时生成新的状态,并计算其启发值,如果该状态未被访问过,则加入队列中。如果搜索到目标状态,则输出操作序列并退出循环。