题目链接:
http://poj.org/problem?id=2488
大致题意:
输入p,q,分别作为行列组成一个棋盘,现在骑士是按照象棋里的马走日的走法移动。问你骑士能不能遍历棋盘上的所有格子,如果能,按照字典序输出路径,如果不能则输出''impossible‘’
解题思路:
字典序即下面的排序。设置一个标志数组,标记走过的路径,然后采用深度搜索的方式看看能否遍历所有棋子。
AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int p, q, flag; //p,q分别为棋盘的行列
int visit[30][30];
int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
struct node {
int x;
int y;
} chess[30];
void dfs(int x, int y, int step)
{
//把当前路径存入结构体中
chess[step].x = x;
chess[step].y = y;
//遍历完所有格子后打印路径
if(step == p * q) {
for(int i = 1; i <= step; i++) {
cout << char(chess[i].y-1+'A') << chess[i].x;
}
cout << endl;
flag = 1;
}
if(flag)
return;
for(int i = 0; i < 8; i++) {
int X = x + dx[i];
int Y = y + dy[i];
//判断是否越界
if(X > 0 && X <= p && Y > 0 && Y <= q && visit[X][Y] == 0) {
visit[X][Y] = 1;
dfs(X, Y, step + 1);
visit[X][Y] = 0;
}
}
}
int main()
{
int n;
int Case = 1;
cin >> n;
while(n--) {
memset(visit, 0, sizeof(visit));
flag = 0;
cin >> p >> q;
cout << "Scenario #" << Case++ << ":" << endl;
visit[1][1] = true;
dfs(1, 1, 1);
if(flag == false)
cout << "impossible" << endl;
cout << endl;
}
return 0;
}