求调。
查看原帖
求调。
936249
zhangqiuyanAFOon2024楼主2024/8/9 16:02
#include<bits/stdc++.h>
using namespace std;
int dx[]={0,0,-1,1},dy[]={1,-1,0,0};
queue<string>q[2];
string s;
string b="123804765";
map<string,int>mp[2];
int extend(int k){
	queue<string> &Q=q[k];
	int dep=mp[k][Q.front()];
	while(Q.size()&&dep==mp[k][Q.front()]){
		string now=Q.front();
		q[k].push(now);
		Q.pop();
		if(mp[k^1].count(now)) return mp[k][now]+mp[k^1][now];
		int x,y;
		for(int i=0;i<9;i++)
			if(now[i]==0){
				x=i/3;
				y=i%3;
				break;
			}
		for(int i=0;i<4;i++){
			int fx,fy;
			fx=x+dx[i];fy=y+dy[i];
			if(fx<0||fy<0||fx>2||fy>2) continue;
			swap(now[x*3+y],now[fx*3+fy]);
			if(mp[k].count(now)){
				swap(now[x*3+y],now[fx*3+fy]);
				continue;
			}
			Q.push(now);
			mp[k][now]=dep+1;
			swap(now[x*3+y],now[fx*3+fy]);
		}
	}
	return -1;
}
void dfs(){
	q[0].push(s);
	mp[0][s]=0;
	q[1].push(b);
	mp[1][b]=0;
	while(q[0].size()&&q[1].size()){
		int t;
		if(q[0].size()<=q[1].size()) t=extend(0);
		else t=extend(1);
		if(t!=-1){
			cout<<t;
			exit(0);
		} 
	}
}
int main(){
	cin>>s;
	dfs();
}
2024/8/9 16:02
加载中...