#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll maxx = 1e9;
int n, m, T;
const int INF = 0x3f3f3f3f;
const double pi = acos(-1.0);
int dx[4] = { 0 , 1 , -1 , 0 }, dy[4] = { 1 , 0 , 0 , -1 };
int bfs(string start)
{
string end = "12345678x";
//定义目标状态
queue<string> q;
unordered_map<string, int> d;
//将字符串和数字相关联,字符串表示状态,数字表示距离
q.push(start);//将其推入初始队列
d[start] = 0;
while (q.size())
{
string t = q.front();//现在对队头进行遍历
q.pop();//记录了之后就可以推出
//记录当前的距离和, 如果是最终状态就返回距离
int dis = d[t];
if (t == end)//符合条件返回步数,也是结束递归的条件
{
return dis;
}
//状态转移
//查询x在字符串中的下标,然后转化为在矩阵中的坐标
int k = t.find('x');//找到目前的我能移动的那个x的位置
int x = k / 3, y = k % 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)
{
//转移x
swap(t[k], t[a * 3 + b]);
//如果当前状态是第一次遍历,记录距离,入队
if (!d.count(t))
{
d[t] = dis + 1;
q.push(t);
}
//还原状态,为下一次转换做准备
swap(t[k], t[a * 3 + b]);
}
}
}
//无法转换到目标
return -1;
}
void solve()
{
string c, start;
for (int i = 0; i < 9; i++)
{
cin >> c;
start += c;//初始状态
}
cout << bfs(start) << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//cin >> T;
//while (T--)
//{
solve();
//}
return 0;
}
八数码(bfs + map优化)(dddd)
最新推荐文章于 2024-09-13 13:21:04 发布