骑士<span class="crawlInfo" id="crawling" style="display: none;"><strong><span style="color:green;">Crawling in process...</span></strong> </span> <span class="crawlInfo" id="crawlFailed" style="display: none;"><strong><span style="color:red;">Crawling failed</span></strong> </span> <span class="crawlInfo" id="crawlSuccess" style="display: inline;"><strong>Time Limit:</strong><span id="timeLimit">5000</span>MS <strong>Memory Limit:</strong><span id="memoryLimit">32768</span>KB <strong>64bit IO Format:</strong><span id="_64IOFormat">%I64d & %I64u</span> </span>
Description
在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相差为2,纵坐标相差为1的格子)移动到空位上。
给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘: 为了体现出骑士精神,他们必须以最少的步数完成任务。
Input
第一行有一个正整数T(T<=10) 表示一共有T组数据 接下来有T个5*5的矩形。0表示白色骑士1表示黑色骑士,*表示空位。(每组数据间有空行)
Output
对每组数据都输出一行。如果能在15不以内(包括15)到达目标状态,则输出步数,否则输出“Bored!”没有引号。
Sample Input
2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
Sample Output
7
Bored!
Bored!
一道搜索题,虽然要求是15步以内但如果是直接BFS或者DFS,时间复杂度大概会达到8^15会TLE,所以需要剪枝,也可以双向BFS搜索(见灿哥的博客点击打开链接)。两种图完全一样的情况可以用两个for循环来对比,剪枝直接从for(1.。。15)进入搜索,即是走1,2,3.。。。15步时能否达到此状态,如果此时的图中棋子的不同数比步数大说明现在的步数不能将棋子还原故而可以减去(移动一步最多改变两个棋子)。
#include<stdio.h>
int map[5][5],ans[5][5]={{1,1,1,1,1},{0,1,1,1,1},{0,0,2,1,1},{0,0,0,0,1},{0,0,0,0,0}}; //原来的状态
int dir[8][2]={1,2,2,1,-1,2,2,-1,-2,-1,-1,-2,-2,1,1,-2}; //方向数组
int anst,xx,yy,m;
int duibi()//对比函数
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
if(map[i][j]!=ans[i][j])
return 0;
return 1;
}
int jianzhi(int s)//剪枝,去掉不可能的情况,优化时间
{
int c=0;
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
if(map[i][j]!=ans[i][j])
{
c++;
if(c+s>m)
return 0;
}
}
return 1;
}
void DFS(int s,int x,int y)
{
if(anst==1) return ;
if(s==m)
{
if(duibi()==1)
anst=1;
return ;
}
for(int i=0;i<8;i++)
{
int px=x+dir[i][0];
int py=y+dir[i][1];
if(px<0||px>=5||py<0||py>=5) continue;
int mid;
mid=map[px][py];
map[px][py]=map[x][y];
map[x][y]=mid;
if(jianzhi(s)==1) DFS(s+1,px,py);
mid=map[px][py];
map[px][py]=map[x][y];
map[x][y]=mid;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
anst=0;
char k[10];
int i,j;
for(i=0;i<5;i++)
{
scanf("%s",k);
for(j=0;j<5;j++)
{
if(k[j]=='*') {map[i][j]=2;xx=i;yy=j;}
else map[i][j]=k[j]-'0';
}
}
if(duibi()==1)
{
printf("0\n");
anst=1;
}
else
for(m=1;m<=15;m++)
{
DFS(0,xx,yy);
if(anst==1)
{
printf("%d\n",m);
break;
}
}
if(anst==0)
printf("Bored!\n");
}
return 0;
}