【BZOJ1085】迭代加深+启发式搜索

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10;
int dx[]={1,1,-1,-1,2,2,-2,-2};
int dy[]={2,-2,2,-2,1,-1,1,-1};
char G[maxn][maxn];
bool found = false;
char a[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','0','1',
'0','0','0','0','0','0'};
bool check()
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(G[i][j]!=a[i][j]) return false;
}
}
return true;
}
bool eva(int now,int t)
{
int cnt = 0;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(G[i][j]!=a[i][j]) cnt++;
}
}
if(cnt+now>t) return false;
return true;
}
void dfs(int x,int y,int t,int stp)
{
if(t==stp)
{
if(check()) found = true;
return;
}
if(found) return;
for(int i=0;i<8;i++)
{
int nx = x+dx[i];
int ny = y+dy[i];
if(nx>=1 && nx<=5 && ny>=1 && ny<=5)
{
swap(G[nx][ny],G[x][y]);
if(eva(stp,t)) dfs(nx,ny,t,stp+1);
swap(G[nx][ny],G[x][y]);
}
}
}
int main(http://www.my516.com)
{
int T;
cin>>T;
while(T--)
{
int sx,sy;
found = false;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
cin>>G[i][j];
if(G[i][j]=='*') sx = i,sy = j;
}
}
for(int i=0;i<=15;i++)
{
dfs(sx,sy,i,0);
if(found)
{
printf("%d\n",i);
break;
}
}
if(!found) printf("-1\n");
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

---------------------

posted @ 2019-06-30 11:18  水至清明  阅读(98)  评论(0编辑  收藏