A Knight's Journey(DFS)深搜
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 33634 | Accepted: 11450 |
Description

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.
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
Source
TUD Programming Contest 2005, Darmstadt, Germany
题意:
背景
骑士越来越无聊的一次又一次看到相同的黑白方块,并决定旅行
世界各地。当骑士移动,它是在一个方向和一个广场两个正方形垂直于这一点。骑士是棋盘的世界他是生活在。我们的骑士生活的棋盘上小面积比普通8
* 8,但它仍然是矩形。你能帮助这个冒险的骑士做旅行计划吗?
找到一个路径,骑士访问每各方格。骑士可以在任何方格开始和结束。
输入输出解释:
首先输入一个n代表的代表一个有几组测试用例。
接下来每组的输入为一个p, q
代表着小于8 * 8 的p * q的棋盘。
问你能不能遍历整个棋盘的每一个方格,如果能输出路径,不能则输出impossible.
对于这道题目来说,刚开始看没有理解是怎么走的,因为正常的思维都是在线上走,那么这里我们可以把格子虚拟成为线,
那么画出图来,就是在线上走的了,这样会好理解的多。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAXN 50
using namespace std;
int x_move[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; //优先向字典序小的方向搜索,有点贪心,呵呵
int y_move[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
bool Map[30][30], flag;
int r, c;
char res[100];
void dfs (int x, int y, int step, int k)
{
if (flag)
return ;
res[k] = x + ‘A‘, res[k+1] = y + ‘1‘; //记录路径
if (step == r * c) //走完全部格子,说明成功
{
flag = true;
return ;
}
int i, tx, ty;
for (i = 0; i < 8; i++)
{
tx = x + x_move[i];
ty = y + y_move[i];
if (tx >= 0 && ty >= 0 && tx < r && ty < c)
{
if (!Map[tx][ty])
{
Map[tx][ty] = true;
dfs (tx, ty, step+1, k+2);
Map[tx][ty] = false;
}
}
}
}
int main()
{
int t, k = 1;
cin >> t;
while (t--)
{
cin >> c >> r;
memset (Map, false, sizeof(Map));
Map[0][0] = true;
flag = false;
dfs (0, 0, 1, 0);
cout << "Scenario #" << k++ << ":\n";
if (!flag)
cout << "impossible\n";
else
{
res[2*r*c] = 0; //封好字符串
cout << res << endl;
}
cout << endl;
}
return 0;
}
原文:http://blog.csdn.net/u012965373/article/details/45047745