九宫重排(BFS)

#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;
}

    原文作者:九宫格问题
    原文地址: https://blog.csdn.net/qq_29169749/article/details/72565718
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞