您的位置:首页 > 其它

poj 2488 A Knight's Journey 水DFS

2016-07-10 16:59 381 查看
传送门:poj 2488 A Knight’s Journey

题目大意

有一个p*q的棋盘,有一个棋子只能走日字形,请问这个棋子能遍历完这个棋盘么,

行是按照大写字母的顺序也就是A,B。。。一直有p个

列是按照数字的顺序也就是1,2,。。。q 有q个

如果能遍历完这个棋盘输出遍历的路径。

如果不能输出impossible

输出的格式按照题目中给定的

解题思路

简单地DFS也没有什么坑

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 200005;
#define lson left,mid,rt<<1
#define rson mid+1,right,rt<<1|1
int path[25][2];
int vis[25][25];
int p,q;
bool flag;
int dirX[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int dirY[8] = {-2, -2, -1, -1, 1, 1, 2, 2};

void dfs(int row,int col,int step)
{
path[step][0] = row;
path[step][1] = col;
if(step ==(p*q))
{
//如果遍历完毕,回到主函数输出
flag = true;
return ;
}
else
{
for(int i=0;i<8;i++)
{
int tempRow = row + dirX[i];
int tempCol = col + dirY[i];
if(!vis[tempRow][tempCol] && tempRow>=1 && tempRow<=p && tempCol >=1 && tempCol<=q && !flag)
{
vis[tempRow][tempCol] = true;
dfs(tempRow,tempCol,step+1);
vis[tempRow][tempCol] = false;
}
}
}

}

/**
*path[x][0]记录的是x的行位置
*path[x][1]记录的是x的列位置
*/

int main()
{
int t;
int cnt = 1;
scanf("%d",&t);
while(t--)
{
flag = false;
scanf("%d%d",&p,&q);
memset(vis,false,sizeof(vis));
vis[1][1] = true;
dfs(1,1,1);
printf("Scenario #%d:\n",cnt++);
if(flag)
{
for(int i=1;i<=p*q;i++)
printf("%c%d",path[i][1]-1+'A',path[i][0]);
}
else
printf("impossible");
printf("\n");
//这也饿算是一个坑,如果不做下面处理的话会出现Presentation Error
//Presentation Error出现的原因是说明结果已经和,要求的结果相当类似了,就是可能多一些或者少一些空格或者回车
if(t != 0)
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: