求条
2026-03-23 21:51:28
发布于:上海
17阅读
0回复
0点赞
不要看我过了这题,打表过的(Doge)
TLE求条
#include<bits/stdc++.h>
using namespace std;
int T,n=5,depth,goal[6][6]={{0,0,0,0,0,0},{0,1,1,1,1,1},{0,0,1,1,1,1},{0,0,0,2,1,1},{0,0,0,0,0,1},{0,0,0,0,0,0}},t[8][2]={{-1,-2},{-1,2},{-2,1},{-2,-1},{1,-2},{1,2},{2,-1},{2,1}};
int a[6][6];
char c[6][6];
bool flag=false;
void dfs(int d,int x,int y)
{
if(flag)return;
int mn=0;
for(int i=1;i<=5;i++)for(int j=1;j<=5;j++)mn=mn+(a[i][j]!=goal[i][j]);
mn=(mn+1)/2;
if(d>depth)return;
if(depth<d+mn)return;
if(d==depth)
{
flag=true;
return;
}
for(int i=0;i<8;i++)
{
int nx=x+t[i][0],ny=y+t[i][1];
if(nx<1 || nx>5 || ny<1 || ny>5)continue;
swap(a[x][y],a[nx][ny]);
dfs(d+1,nx,ny);
swap(a[x][y],a[nx][ny]);
}
return;
}
int main()
{
cin>>T;
while(T--)
{
flag=false;
int x,y;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>c[i][j];
if(c[i][j]=='1')a[i][j]=1;
else if(c[i][j]=='0')a[i][j]=0;
else
{
a[i][j]=2;
x=i,y=j;
}
}
}
for(depth=0;depth<=15;depth++)
{
dfs(0,x,y);
if(flag)break;
}
if(flag)cout<<depth<<endl;
else cout<<-1<<endl;
}
return 0;
}
全部评论 2
666
1周前 来自 浙江
0记忆化
1周前 来自 广东
0感谢,加了记忆化过了
1周前 来自 上海
0羡慕会记忆化
1周前 来自 广东
0













有帮助,赞一个