玄关,折半bfs0分求调QAQ
查看原帖
玄关,折半bfs0分求调QAQ
1122029
icebear233楼主2025/7/24 16:29
#include<bits/stdc++.h>
using namespace std;
string mb="111110111100*110000100000";
int T;
bool flag;
unordered_map<string,int> mp;
unordered_map<string,bool> vis;
int d[8]={-11,-9,-7,-3,11,9,7,3};
int ans=INT_MAX;
struct node{
	string s;
	int st,w;
};
queue<node> q;
void Main(){
	ans=INT_MAX;
	mp.clear();
	vis.clear();
	string s,s1,s2,s3,s4,s5;
	cin>>s1>>s2>>s3>>s4>>s5;
	s=s1+s2+s3+s4+s5;
	flag=0;
	int x;
	for(int i=0;i<25;i++){
		if(s[i]=='*'){
			x=i;
			break;
		}
	}
	node t,tt;
	//bfs1
	t.s=s;
	t.st=0;
	t.w=x;
	q.push(t);
	while(!q.empty()){
		t=q.front();
		q.pop();
		if(t.st>7){
			continue;
		}
		if(t.s==mb){
			cout<<t.st<<"\n";
			return ;
		}

		mp[t.s]=t.st;
		for(int i=0;i<8;i++){
			tt.s=t.s;
			tt.st=t.st+1;
			tt.w=t.w+d[i];
			if(tt.w<0||tt.w>24||mp[tt.s]){
				continue;
			}
			swap(tt.s[tt.w],tt.s[t.w]);
			q.push(tt);
		}
	}
	//bfs2
	t.s=mb;
	t.st=0;
	t.w=12;
	q.push(t);
	while(!q.empty()){
		t=q.front();
		q.pop();
		if(t.st>8){
			continue;
		}
		if(mp[t.s]!=0){
			cout<<t.st+mp[t.s]<<"\n";
			return ;
		}
		vis[t.s]=1;
		mp[t.s]=t.st;
		for(int i=0;i<8;i++){
			tt.s=t.s;
			tt.st=t.st+1;
			tt.w=t.w+d[i];
			if(tt.w<0||tt.w>24||vis[tt.s]){
				continue;
			}
			swap(tt.s[tt.w],tt.s[t.w]);
			q.push(tt);
		}
	}
	cout<<-1<<"\n";
	return ;
}



int main(){
	ios::sync_with_stdio(0);
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	cin>>T;
	while(T--){
		Main();
	}
	return 0;
}
2025/7/24 16:29
加载中...