[sicily]1152. 简单的马周游问题
2015-10-14 16:30
381 查看
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
注意:如果起点和输入给定的不同,重复多次经过同一方格或者有的方格没有被经过,都会被认为是错误的。
典型的深度优先搜索的回溯算法题,由于数据量比较小,直接进行搜索也能以 0.45s 左右的时间AC。采用递归写法,直接对八个方向进行搜索,利用color[][] 数组标记已访问过的地方,自定义check 函数判断是否能访问下一地方。代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int color[5][6];
int movex[8] = {-2,-2,-1,-1,1,1,2,2};
int movey[8] = {-1,1,-2,2,-2,2,-1,1};
int path[31];
int flag = 0;
bool check(int x, int y)
{
if( x<0 || x>4 || y<0 || y>5 )
return false;
if(color[x][y] == 1)
return false;
return true;
}
void dfs(int x, int y, int index)
{
color[x][y] = 1;
path[index] = 6*x + y + 1;
if(flag==1)
return ;
if(index == 30)
{
flag = 1;
for(int i=1; i<30; i++)
cout<<path[i]<<" ";
cout<<path[30]<<endl;
}
else
{
for(int i=0; i<8; i++)
{
if(check(x+movex[i], y+movey[i]))
dfs(x+movex[i], y+movey[i], index+1);
}
color[x][y] = 0;
}
}
int main()
{
int n;
while(cin>>n && n!=-1)
{
int index = 0;
memset(color,0, sizeof(color));
int x = n/6;
int y = n%6-1;
if(y<0) y = 5;
flag = 0 ;
dfs(x,y,index+1);
}
//system("pause");
return 0;
}
相关文章推荐
- sicily 1020. Big Integer
- soj1041. Pushing Boxes
- Sicily 1046, Plane Spotting
- SICILY 1934 移动小球
- 1920. Divide The Stones
- 1801. Reading books
- 1874. Three little pigs
- Sicily 1121. Tri Tiling
- Sicily 1090. Highways
- Sicily 1155. Can I Post the lette
- Sicily 1200. Stick
- Sicily 1342. 开心的金明
- Sicily 1153. 马的周游问题
- Sicily 1171. The Game of Efil
- 1007[To and Fro]
- 1014[Specialized Four-Dig]
- 1024[MJ, Nowhere to Hide]
- 1036[Crypto Columns]
- 1147[谁拿了最多奖学金]
- 1157[The hardest problem]