A*模板样例全-1求调 ,悬赏关注
查看原帖
A*模板样例全-1求调 ,悬赏关注
732988
JacoAquamarine楼主2023/7/16 10:33

RT ,好像是主函数while里少了啥。

#include<iostream>
using namespace std;
int T;
const char chk[6][6]={
	'0','0','0','0','0','0',
	'0','1','1','1','1','1',
	'0','0','1','1','1','1',
	'0','0','0','*','1','1',
	'0','0','0','0','1','1',
	'0','0','0','0','0','1'
};
const int dx[9]={0,-2,-2,-1,-1,1,1,2,2};
const int dy[9]={0,-1,1,-2,2,-2,2,-1,1};
int ans;
char map[6][6];
int diff(){
	int ans=0;
	for(int i=1;i<=5;i++){
		for(int j=1;j<=5;j++){
			if(map[i][j]!=chk[i][j])ans++;
		}
	}
	return ans;
}
void dfs(int x,int y,int step,int d){
	int h=diff();
	if(step+h>16)return ;
	if(step+h-1>=ans&&ans!=-1)return ;
	if(h==0){
		ans=step;
		return ;
	}
	for(int i=1;i<=8;i++){
		int tx=x+dx[i];
		int ty=y+dy[i];
		if(tx>=1&&tx<=5&&ty>=1&&ty<=5&&d+i!=9){
			swap(map[x][y],map[tx][ty]);
			dfs(tx,ty,step+1,i);
			swap(map[x][y],map[tx][ty]);
		}
	}
}
int main(){
	cin.tie(0);
	cin>>T;
	while(T--){
		int x,y;
		ans=-1;
		for(int i=1;i<=5;i++){
			for(int j=1;j<=5;j++){
				cin>>map[i][j];
				if(map[i][j]='*'){
					x=i;
					y=j;
				} 
			}
		}
		dfs(x,y,0,0);
		cout<<ans<<'\n';
	}
	return 0;
} 
2023/7/16 10:33
加载中...