Description
BackgroundThe 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.
Input
Output
If no such path exist, you should output impossible on a single line.
Sample Input
3 1 1 2 3 4 3
Sample Output
Scenario #1: A1 Scenario #2: impossible Scenario #3: A1B3C1A2B4C2A3B1C3A4B2C4
这道题为一道DFS题,要求骑士能把所有方格走一遍,输出一种走的路径。思路就是从A1开始向8个方位搜索,若满足条件,则跳过去,直到把所有格子跳一遍为止。
源代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
int p,q,h,z,b[100][100],a2[100],f[10][10]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
char a1[100];
void DFS(int x,int y,int h)
{
int i,j;
if(h==p*q)
{
for(i=0;i<h;++i)
cout<<a1[i]<<a2[i];
cout<<endl;
z=0;
}
else for(i=0;i<8;++i)
{
if(x+f[i][0]>=1&&x+f[i][0]<=p&&y+f[i][1]>=1&&y+f[i][1]<=q&&b[x+f[i][0]][y+f[i][1]]==0&&z)
{ b[x+f[i][0]][y+f[i][1]]=1;
a1[h]=y+f[i][1]-1+'A';
a2[h]=x+f[i][0];
DFS(x+f[i][0],y+f[i][1],h+1);
b[x+f[i][0]][y+f[i][1]]=0;
}
}
}
int main()
{
int n,k=0;
cin>>n;
while(n--)
{ k++;
z=1;
memset(a1,'\0',sizeof(a1));
memset(a2,0,sizeof(a2));
a1[0]='A';
a2[0]=1;
memset(b,0,sizeof(b));
b[1][1]=1;
cin>>p>>q;
cout<<"Scenario #"<<k<<":"<<endl;
DFS(1,1,1);
if(z)cout<<"impossible"<<endl;
if(n!=0)cout<<endl;
}
}
这篇博客介绍了一道使用深度优先搜索(DFS)解决的C++编程问题。题目要求找出棋盘上骑士能够遍历所有方格的路径。通过从A1位置开始,向8个可能的方向进行搜索,如果满足条件则跳转,直至遍历完所有格子。源代码中定义了DFS函数,遍历过程会记录路径并输出。在主函数中,程序读取输入并调用DFS进行求解,对于无法找到遍历路径的情况,输出"impossible"。
1769

被折叠的 条评论
为什么被折叠?



