萌新刚学双向BFS,9分求助
查看原帖
萌新刚学双向BFS,9分求助
546681
lcbridgeAK CSP-S楼主2023/7/27 16:03
#include <bits/stdc++.h>
#define int long long
#define END 123804765
using namespace std;
const int N=1e5+5;
int I,walk[5][2]={{1,0},{-1,0},{0,1},{0,-1}};
map <int,int> ans;
map <int,int> S;
int To_int(int A[][4]){
	int sum=0,w=1e8;
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			sum+=A[i][j]*w;
			w/=10;
		}
	}
	return sum;
}
void bfs(){
	queue <int> q;
	q.push(I);
	q.push(END);
	ans[END]=1;
	S[I]=1;
	S[END]=2;
	while(!q.empty()){
		int x=q.front();q.pop();
		int xx=x,fx,fy,A[4][4];
		//cout<<S[xx]<<' '<<E[xx]<<' '<<xx<<"\n"; 
		string sx="";
		while(xx){
			sx+=((xx%10)+'0');
			xx/=10;
		}
		reverse(sx.begin(),sx.end());
		int t=0;
		//cout<<sx<<"\n"; 
		for(int i=1;i<=3;i++){
			for(int j=1;j<=3;j++){
				A[i][j]=(sx[t++]-'0');
			}
		}
		for(int i=1;i<=3;i++){
			for(int j=1;j<=3;j++){
				if(!A[i][j]){
					fx=i,fy=j;
					break;
				}
			}
		}
		//cout<<fx<<' '<<fy<<"\n";
		for(int i=0;i<4;i++){
			int nx=walk[i][0]+fx;
			int ny=walk[i][1]+fy;
			if(nx<1||nx>3||ny<1||ny>3)continue; 
			swap(A[fx][fy],A[nx][ny]);
			int nb=To_int(A);
			//cout<<nb<<' '<<x<<"\n";
			if(S[nb]==S[x]){
				swap(A[fx][fy],A[nx][ny]);
				continue;
			}
			if(S[nb]+S[x]==3){
				cout<<ans[x]+ans[nb];
				exit(0);
			}
			S[nb]=S[x];
			ans[nb]=ans[x]+1;
			q.push(nb);
			swap(A[fx][fy],A[nx][ny]);
		} 
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin>>I;
	bfs();
	return 0;
} 
2023/7/27 16:03
加载中...