DFS求调
查看原帖
DFS求调
763878
Jerry_heng楼主2024/3/6 16:59
#include<bits/stdc++.h>
using namespace std;
map<string,bool>mp;
int ans=INT_MAX,f[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
string end;
void dfs(string st,int step){
	if(mp[st])return;
	mp[st]=1;
	if(st==end){
		ans=min(ans,step);
		return;
	}
	if(step>=ans)return;
	int pos;
	for(int i=0;i<9;i++)
		if(st[i]=='0')pos=i;
	int x=pos/3,y=pos%3;
	for(int i=0;i<4;i++){
		int xx=x+f[i][0],yy=y+f[i][1];
		if(0<=xx&&xx<3&&0<=yy&&yy<3){
			int poss=xx*3+yy;
			string stt=st;
			swap(stt[pos],stt[poss]);
			dfs(stt,step+1);
		}
	}
}
int main(){
	ios::sync_with_stdio(0);
	string st;
	cin>>st;
	end="123804765";
	dfs(st,0);
	cout<<ans;
	return 0;
}
2024/3/6 16:59
加载中...