样例不过,排了2天求调
查看原帖
样例不过,排了2天求调
194756
dino楼主2023/10/17 19:40
#include<bits/stdc++.h>
using namespace std;
struct node{
	int way; 
	string mp;
	bool operator < (const node &x) const {  
        return way > x.way;        
    }  
};
int g[9] = {0, -1, -2, -2, -1, +1, +2, +2, +1};
int f[9] = {0, -2, -1, +1, +2, +2, +1, -1, -2};
int const N = 6 + 5;
int const SIZ = 5;
string const s = "111110111100*110000100000";
map<string, int> mp;
char b[N][N];
string zhuan(){
	string v = "";
	for(int i = 0; i < SIZ; i++){
		for(int j = 0; j < SIZ; j++){
			v += b[i][j];
		}
	}
	return v;
}
int h(string v){
	int cnt = 0;
	for(int i = 0; i < SIZ * SIZ; i++){
		if(s[i] != v[i]) cnt++;
	}
	return cnt;
}
int main(){
	int T;
	cin >> T;
	while(T--){
		string t = "";
		for(int i = 0; i < SIZ; i++){
			for(int j = 0; j < SIZ; j++){
				cin >> b[i][j];
			}
		}
		mp.clear();
		t = zhuan();
		priority_queue<node> q;
		mp[t] = 1;
		q.push((node){0, t});
		while(!q.empty()){
			node u = q.top();
			q.pop();
			if(mp[u.mp] == 16){
				cout << -1 << endl;
				break;
			}
			if(u.mp == s){
				cout << mp[u.mp] - 1 << endl;
				break;
			}
			int ux, uy;
			for(int i = 0; i < SIZ; i++){
				for(int j = 0; j < SIZ; j++){
					b[i][j] = u.mp[i * SIZ + j]; 
					if(b[i][j] == '*'){
						ux = i;
						uy = j;
					}
				}
			}
			for(int i = 1; i <= 8; i++){
				int da = ux + g[i];
				int db = uy + f[i];
				if(da < 0 || db < 0 || da >= SIZ || db >= SIZ) continue;
				swap(b[ux][uy], b[da][db]);
				string v = zhuan();
				swap(b[ux][uy], b[da][db]);
				if(mp[v]) continue;
				q.push((node){h(v), v});
				mp[v] = mp[u.mp] + 1;
			}
		}
	}
} 
2023/10/17 19:40
加载中...