原题:
Background
The knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. Can you help this adventurous knight to make travel plans?
Problem
Find a path such that the knight visits every square once. The knight can start and end on any square of the board.
题解:
象棋,马走日的问题,输入一个n代表棋盘的大小,然后马从A1也就是第一行第一列开始走,问怎么走才能走完整个棋盘的每一个位置。
题解:
要注意按照字典序的输出,也就是深搜的步骤必须按照我代码中所设置的fx,fy的顺序来进行搜索,开始没注意,随便设置的方向,wa了。主体还是深搜,截止条件是遍历的所有的格子,就可以输出顺序了,没遍历完就继续在可以走的八个方向遍历,同时可以直接在棋盘上记录顺序,然后输出的是否不断找下一个数字,(虽然效率不太高)。
代码:AC
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int fy[]={-2,-2,-1,-1,1,1,2,2};
int fx[]={-1,1,-2,2,-2,2,-1,1};
int board[30][30];
int flag=0;
int n,m;
void DFS(int x,int y,int cnt)
{
int i,j,k;
if(flag)
return;
if(cnt==n*m)
{
for(k=1;k<=n*m;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(k==board[i][j])
printf("%c%d",'A'-1+j,i);
}
}
}
cout<<endl;
flag=1;
return;
}
for(i=0;i<8;i++)
{
int dx=x+fx[i];
int dy=y+fy[i];
if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&!board[dx][dy])
{
board[dx][dy]=cnt+1;
DFS(dx,dy,cnt+1);
board[dx][dy]=0;
}
}
}
int main()
{
int t,k,i,j;
cin>>t;
for(k=1;k<=t;k++)
{
cin>>n>>m;
cout<<"Scenario #"<<k<<':'<<endl;
if(n==1&&m==1)
{
cout<<"A1"<<endl;
}
else if(n==1||m==1)
{
cout<<"impossible"<<endl;
}
else{
memset(board,0,sizeof(board));
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
board[i][j]=1;
flag=0;
DFS(i,j,1);
if(flag)
break;
memset(board,0,sizeof(board));
}
if(j<=m)
break;
}
if(i>n)
cout<<"impossible"<<endl;
}
cout<<endl;
}
return 0;
}