c九宫重排_九宫重排(BFS)

#include

#include

#include

#include

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;

elseh = h * 10 + (s[i] - '0');

}

return h;

}

int bfs(Node s)

{

queue que;

set 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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值