Sicily 1152.简单的马周游问题
2014-09-20 23:05
393 查看
1152. 简单的马周游问题
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB , Special JudgeDescription
在一个5 * 6的棋盘中的某个位置有一只马,如果它走29步正好经过除起点外的其他位置各一次,这样一种走法则称马的周游路线,试设计一个算法,从给定的起点出发,找出它的一条周游路线。为了便于表示一个棋盘,我们按照从上到下,从左到右对棋盘的方格编号,如下所示:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
马的走法是“日”字形路线,例如当马在位置15的时候,它可以到达2、4、7、11、19、23、26和28。但是规定马是不能跳出棋盘外的,例如从位置1只能到达9和14。
Input
输入有若干行。每行一个整数N(1<=N<=30),表示马的起点。最后一行用-1表示结束,不用处理。Output
对输入的每一个起点,求一条周游线路。对应地输出一行,有30个整数,从起点开始按顺序给出马每次经过的棋盘方格的编号。相邻的数字用一个空格分开。Sample Input
4-1
Sample Output
注意:如果起点和输入给定的不同,重复多次经过同一方格或者有的方格没有经过,都会被认为是错误的。这题主要用DFS,因为棋盘大小只有5×6,所以进行回溯时没有进行剪枝,不过也能通过,但是时间会比较久。
#include "iostream" using namespace std; #define row 5 #define colum 6 typedef struct //存储方向的结构体 { int x; //方向x值 int y; //方向y值 }array; array direction[8]; //声明一个数组用来存储8个方向 bool flag[row * colum]; //设置一个是否已经入队的标记 int dir[row * colum]; //存储马行走的路径 bool finish = false; //结束标记 void initial() { direction[0].x = 2; direction[0].y = 1; direction[1].x = 1; direction[1].y = 2; direction[2].x = -1; direction[2].y = 2; direction[3].x = -2; direction[3].y = 1; direction[4].x = -2; direction[4].y = -1; direction[5].x = -1; direction[5].y = -2; direction[6].x = 1; direction[6].y = -2; direction[7].x = 2; direction[7].y = -1; } int change(array now) //坐标转换函数 { return (now.x * colum + now.y + 1); //将二维坐标转换为一维坐标 } void search(array now, int k) //进行回溯 { array next; if(finish == true) return; if(k == row * colum) //k已经到头 { finish = true; for (int i = 0; i < row * colum - 1; i++) cout<<dir[i]<<" "; cout<<dir[row * colum - 1]<<endl; } else { for (int i = 0; i < 8; i++) { next.x = now.x + direction[i].x; next.y = now.y + direction[i].y; int n = change(next); //计算出一维坐标 if(next.x >= 0 && next.x < row && next.y >=0 && next.y < colum && !flag ) { flag = true; //将next标记为走过 dir[k] = n; //记录下马行走的路径 k++; search(next,k); flag = false; //如果从上一层回溯出来,则将上一个n置false,也将k-- k--; } } } } int main() { initial(); //方向初始化 array start; //声明开始节点 int n;//输入起点 cin>>n; while (n != -1) { start.x = (n - 1) / colum; //坐标转换 start.y = (n -1) % colum; for (int i = 0; i < row*colum; i++) { flag[i] = false; //将flag标记初始化为false } finish = false; //结束标记为false dir[0] = n; //路径第一个数字为起点 flag = true; search(start,1); cin>>n; } return 0; }
在回溯的时候,8个方向的点按顺序寻找,所以需要的时间比较久。
相关文章推荐
- <OJ_Sicily>1152简单的马周游问题
- sicily 1152. 简单的马周游问题
- sicily 1152 简单的马周游问题 and sicily 1153 马的周游问题
- sicily 1152 简单的马周游问题
- sicily 1152 简单的马周游问题
- sicily 1152. 简单的马周游问题
- [sicily]1152. 简单的马周游问题
- sicily 1152.简单的马周游问题
- Sicily 1152 简单的马周游问题
- Sicily 1152 简单的马周游问题[Speical judge]
- sicily 1152. 简单的马周游问题[Special judge]
- Sicily 1152. 简单的马周游问题
- Sicily 1152 & 1153 简单的马周游问题
- Sicily 1152 简单的马周游问题
- Sicily 1152 简单的马周游问题[Special judge]
- Sicily 1152. 简单的马周游问题
- sicily 1152 简单的马周游问题 and sicily 1153 马的周游问题
- Sicilly 1152 马的简单周游问题(5*6)
- 1152. 简单的马周游问题
- Sicily 1153 马的周游问题[Special judge] && sicily 1152