样例过不了求调(玄关)
查看原帖
样例过不了求调(玄关)
597555
hzb1121楼主2024/7/2 21:31

IDA*算法,不知道哪错了。而且看很多dalao的题解中估价函数没写 now[i]!='*' 这一句

#include<iostream>
#include<string.h>
#include<map>
using namespace std;
int T,ans=1121;
map<string,int> mp;
string s,ss;
string goal="111110111100*110000100000";
int dx[8]={1,1,2,2,-1,-1,-2,-2};
int dy[8]={2,-2,1,-1,2,-2,1,-1};
int x0,y0,id0;
int h(string now)
{
	int cnt=0;
	for(int i=0;i<25;i++)
	{
		if(now[i]!=goal[i]&&now[i]!='*') cnt++;
		if(now[i]=='*'){
			x0=i/5,y0=i%5,id0=i;
		}
	}
	return cnt;
}
void dfs(string now,int depth,int mxdepth)
{
	if(now==goal)
	{
		ans=depth;
		return;
	}
	if(ans!=1121) return;
	if(depth>=mxdepth) return;
	if(depth+h(now)>mxdepth) return;
	for(int i=0;i<8;i++)
	{
		int nx=x0+dx[i];
		int ny=y0+dy[i];
		if(nx>=0&&nx<=4&&ny>=0&&ny<=4){
			int id=nx*5+ny;
			swap(now[id],now[id0]);
			if(mp[now]==0){
				mp[now]=1;
				dfs(now,depth+1,mxdepth);
				mp[now]=0;
			}
			swap(now[id],now[id0]);
		}
	}
}
int IDAstar()
{
	mp[s]=1;
	for(int i=0;i<=15;i++)
	{
		dfs(s,0,i);
		if(ans!=1121) return i;
	}
	return -1;
}
int main()
{
	cin>>T;
	while(T--)
	{
		for(int i=1;i<=5;i++){
			cin>>ss;
			s+=ss;
		}
		ans=1121;
		mp.clear();
		cout<<IDAstar()<<endl;
	}
	return 0;
}
2024/7/2 21:31
加载中...