poj 2488 A Knight's Journey 水DFS
2016-07-10 16:59
381 查看
传送门:poj 2488 A Knight’s Journey
行是按照大写字母的顺序也就是A,B。。。一直有p个
列是按照数字的顺序也就是1,2,。。。q 有q个
如果能遍历完这个棋盘输出遍历的路径。
如果不能输出impossible
输出的格式按照题目中给定的
题目大意
有一个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; }
相关文章推荐
- jsp九大内置对象及其作用?
- 快速排序
- servlet服务程序
- leetcode.368. Largest Divisible Subset
- 开源项目管理当中最为常见的十类糟糕实践
- 【PHP面向对象(OOP)编程入门教程】12.重载新的方法(parent::)
- 【PHP面向对象(OOP)编程入门教程】11.类的继承
- C语言标准库函数qsort排序的介绍与使用
- Session和cookie的区别(进行对比)
- 希尔排序
- 整数中1出现的次数(从1到n整数中1出现的次数)
- 【PHP面向对象(OOP)编程入门教程】10.__set(),__get(),__isset(),__unset()四个方法的应用
- 探究绑定事件的this指向以及event传参的小问题
- jQuery.ajax()
- leetcode 373 Find K Pairs with Smallest Sums java
- SQL Server中将日期转换成字符串
- WebView的简单使用
- 回弹效果HorizontalScrollview
- 递归
- μCOS/II v2.85内核OSSemPend()和OSSemPost()函数工作原理