八数码 启发式搜索A*/BFS

八数码

题目链接:
描述
八数码 启发式搜索A*/BFS_第1张图片
大佬的参考题解:
题解

#include 
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define INF 0x3f3f3f3f
#define PIS pair<int, string>
#define rep(i, l, r) for (int i = l; i < r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define rep2(i, l, r) for (int i = l; i * i <= r; i++)
#define rep3(i, l, r) for (LL i = l; i * i * i <= r; i++)
#define Min(a, b) a > b ? b : a
#define Max(a, b) a > b ? a : b
#define endl '\n'
#define debug "-----"
using namespace std;
typedef long long LL;
const LL mod = 1e9;
const int N = 1e6 + 10, M = 1050;
LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; }

int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
char oper[] = "udlr";

int f( string s ){
	int d = 0;
	rep( i , 0 , s.size() ){
		if( s[i] != 'x' ){
			int t = s[i]-'1';
			d += abs(i/3-t/3)+abs(i%3-t%3);
		}
	}
	return d;
}

string bfs( string start ){
	unordered_map<string,int> d;
	priority_queue<PIS,vector<PIS>,greater<PIS>>heap;
	unordered_map<string, pair<string, char> > last;

	string end = "12345678x";
	heap.push( {f(start),start} );
	d[ start ] = 0;

	while( heap.size() ){
		auto t = heap.top();
		heap.pop();
		string start = t.second;
		if( start == end ) break;

		int x,y;
		rep( i , 0 , 9 )
			if( start[i]=='x' ){
				x = i/3;
				y = i%3;
				break;
			}

		string init = start;
		rep( i , 0 , 4 ){
			int a = x+dx[i];
			int b = y+dy[i];
			if( a<0||a>=3||b<0||b>=3 ) continue;
			swap( start[a*3+b] , start[x*3+y] );
			if( !d.count(start) || d[start]>d[init]+1 ){
				d[start] = d[init]+1;
				heap.push( {f(start)+d[start],start} );	
				last[ start ] = {init,oper[i]};
			}
			start = init;
		}
	}

	string ans="";
	while( end != start ){
		ans += last[end].second;
		end = last[end].first;
	}
	reverse( ans.begin() , ans.end() );
	return ans;
}

int main()
{
	IOS;
	int ans=0;
	string start,x,c;
	while( cin >> c ){
		start += c;
		if( c != "x" ) x += c;
	}
	rep( i , 0 , x.size() )
		rep( j , i+1 , x.size() )
			if( x[i] > x[j] ) ans++;
	if( ans&1 )
		puts("unsolvable");
	else 
		cout << bfs(start);
	return 0;
}

你可能感兴趣的:(宽度优先,算法,哈希算法,c++)