#include <iostream>
#include <string>
#include <queue>
#include <set>
using namespace std;
struct Node {
string code;
int d;
Node(const string& c, int d): code(c), d(d) {}
Node() {}
};
string bState, eState;
string moveSquare(int d, string s)
{
int blankPos;
for(int i = 0; i < 9; i++)
if(s[i] == '.') { blankPos = i; break; }
if(d == 0 && blankPos >= 3) {
swap(s[blankPos], s[blankPos-3]);
return s;
}
if(d == 1 && blankPos < 6) {
swap(s[blankPos], s[blankPos+3]);
return s;
}
if(d == 2 && blankPos % 3 != 0) {
swap(s[blankPos], s[blankPos-1]);
return s;
}
if(d == 3 && blankPos % 3 != 2) {
swap(s[blankPos], s[blankPos+1]);
return s;
}
return s;
}
inline int getHash(const string& s)
{
int h = 0;
for(int i = 0; i < 9; i++) {
if(s[i] == '.') h = h * 10 + 9;
else h = h * 10 + (s[i] - '0');
}
return h;
}
int bfs(Node s)
{
queue<Node> que;
set<int> closed;
closed.clear();
que.push(s);
//closed.insert(s.code);
while(!que.empty()) {
Node tmp = que.front(); que.pop();
//cout << "#" << tmp.code << endl;
if(tmp.code == eState) return tmp.d;
int h = getHash(tmp.code);
if(closed.find(h) != closed.end()) continue;
closed.insert(h);
for(int i = 0; i < 4; i++) {
string nCode = moveSquare(i, tmp.code);
if(nCode != tmp.code) {
que.push(Node(nCode, tmp.d + 1));
}
}
}
return -1;
}
int main()
{
//freopen("in.txt", "r", stdin);
cin >> bState >> eState;
cout << bfs(Node(bState, 0)) << endl;
return 0;
}
九宫重排(BFS)
最新推荐文章于 2020-10-27 20:57:38 发布
本文介绍了一种使用广度优先搜索(BFS)解决九宫格排列问题的方法。通过创建节点结构、定义移动方格的函数以及哈希函数来避免重复状态,实现了从起始状态到目标状态的最短步数计算。
摘要由CSDN通过智能技术生成