求助IDA*
查看原帖
求助IDA*
378346
expnoi楼主2022/7/4 17:27
#include<bits/stdc++.h>
using namespace std;
int T,sx,sy,dx[10]={-2,-1,1,2,2,1,-1,-2},dy[10]={1,2,2,1,-1,-2,-2,-1},flag;
char a[10][10];
char ch[10][10];
inline int h()
{
	int cnt=0;
	for(int i=1;i<=5;i++)
	{
		for(int j=1;j<=5;j++)
		{
			if(ch[i][j]!=a[i][j])
			{
				cnt++;
			}
		}
	}
	return cnt;
}
inline void dfs(int x,int y,int s,int dep)
{
	if(flag)return;
	int H=h();
	if(dep==7&&H==0)
	{
		cout<<H<<" "<<s<<" "<<dep<<"\n";
		for(int i=1;i<=5;i++)
		{
			for(int j=1;j<=5;j++)
			{
				cout<<a[i][j];
			}
			cout<<"\n";
		}
		cout<<"\n";
	}
	if(H==0)
	{
		flag=1;
		return;
	}
	if(H+s>dep)return;
	for(int i=0;i<8;i++)
	{
		int tx=x+dx[i],ty=y+dy[i];
		if(tx<1||tx>5||ty<1||ty>5)
		{
			continue;
		}
		swap(a[x][y],a[tx][ty]);
		dfs(tx,ty,s+1,dep);
		swap(a[x][y],a[tx][ty]);
	}
}
int main()
{
	cin>>T;
	ch[1][1]=ch[1][2]=ch[1][3]=ch[1][4]=ch[1][5]=ch[2][2]=ch[2][3]=ch[2][4]=ch[2][5]=ch[3][4]=ch[3][5]=ch[4][5]='1';
	ch[2][1]=ch[3][1]=ch[3][2]=ch[4][1]=ch[4][2]=ch[4][3]=ch[4][4]=ch[5][1]=ch[5][2]=ch[5][3]=ch[5][4]=ch[5][5]='0';
	ch[3][3]='*';
	while(T--)
	{
		flag=0;
		for(int i=1;i<=5;i++)
		{
			for(int j=1;j<=5;j++)
			{
				cin>>a[i][j];
				if(a[i][j]=='*')
				{
					sx=i;
					sy=j;
				}
			}
		}
		for(int dep=1;dep<=15;dep++)
		{
			dfs(sx,sy,0,dep);
			if(flag)
			{
				cout<<dep<<"\n";
				break;
			}
		}
		if(!flag)
		{
			cout<<"-1\n";
		}
	}
}
2022/7/4 17:27
加载中...