10分求助,悬关 - 1379 八数码难题
查看原帖
10分求助,悬关 - 1379 八数码难题
921450
Szy0720楼主2023/8/26 14:56
#include<bits/stdc++.h>
using namespace std;
string S="123804765",ss;
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
int bfs(string s){
	if(s==S)return 0;
	map<string,bool>v;//去重
	v[s]=1;
	queue<pair<string,int> >que;
	que.push({s,0});
	while(que.size()){
		string a=que.front().first;
		int b=que.front().second;
		que.pop();
		for(int i=0;i<9;i++){//遍历
			if(a[i]=='0'){//0的情况
				int x=i/3,y=i%3;//行,列
				for(int j=0;j<4;j++){
					int xx=x+dx[i];
					int yy=y+dy[i];
					if(x<0||x>2||y<0||y>2)continue;
					int k=xx*3+yy;
					string Ss=a;
					swap(Ss[i],Ss[k]);
					if(Ss==S)return b+1;
					if(v[Ss]==0){
						v[Ss]=1;
						que.push({Ss,b+1});
					} 
				}
			}	
		}
	}
}
int main(){
	cin>>ss;
	cout<<bfs(ss);
	return 0;
}
2023/8/26 14:56
加载中...