八数码问题
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <string>
using namespace std;
const int maxsize = 10;
int exchange_min(string start)
{
queue<string> q; //队列实现bfs
unordered_map<string, int> dist; //哈希表,表示从初始状态到新的状态的最短距离
string end = "12345678x"; //结束状态
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; //'x'可以移动的位置,上下左右4个方向
q.push(start); //入队
dist[start] = 0; //初始化
while(!q.empty())
{
auto temp = q.front();
q.pop();
int distance = dist[temp];
if(temp == end) return distance;
int k = temp.find('x'); //返回x的位置,从0开始
int x = k / 3, y = k % 3; //计算x的二维坐标,即恢复为3*3矩阵
for(int i = 0; i < 4; i++)
{
int a = x+dx[i], b = y + dy[i]; //获取移动后的位置
if(a >= 0 && a <3 && b >= 0 && b < 3) //若移动后的位置合法
{
swap(temp[k], temp[a * 3 + b]); //交换位置,形成新的状态
if(!dist.count(temp)) //如果新的状态的距离为0
{
dist[temp] = distance + 1; //更新距离,distance是未更新距离
q.push(temp); //将新的状态入队;
}
swap(temp[k], temp[a * 3 + b]); //恢复未移动的状态
}
}
}
return -1; //遍历到最后也没返回即不存在解决方案
}
int main()
{
char c;
string str;
for(int i = 0; i < 9; i++)
{
cin >> c;
str += c;
}
cout << exchange_min(str) << endl;
return 0;
}