URAL 1298 knight dfs搜索

1298. Knight

Time limit: 2.0 second
Memory limit: 64 MB
Even paratroopers have vacations. The flight to Sirius in the depths of “The Admiral Brisco” Leo Hao whiled away with chessboard. No, he did not like usual chess game, and in addition, he did not have likely rival. The whole day Leo amused himself with an interesting thing: he tried to travel over all cells of the chessboard with the knight so that the knight visited each cell only one time. Leo attempted one time, then second, but always something was wrong. Leo became a little angry. Then he attempted board 4*4 instead of 8*8. Again failure after failure. A little angry, with the chessboard under his arm, Leo went to look for a local programmer. They two together indeed will solve this problem.

Input

There is only one number  N (1 ≤  N ≤ 8) in the input.

Output

If it is possible to travel with the knight over the square field  N× N cells, then output should contain  N 2 lines with tour over the chessboard with mentioned property, otherwise the only word “IMPOSSIBLE”.

Samples

input output
3
IMPOSSIBLE
5
a1
c2
e1
d3
e5
c4
d2
e4
c5
a4
b2
d1
e3
d5
b4
a2
c1
e2
c3
b1
a3
b5
d4
b3
a5








题意:有一个n*n的棋盘。从任意一个位置开始走。走法和象棋中的马一样。要求走过的点不能再走。输出可以走完所有点的走法。
否者输出IMPOSSIBLE。


做法:用dfs搜索所有的点。。。  并记录走的路线

不知道为什么dir的方向如果不一样,得到的 时间 差的很远。

我用的两种dir 一个只用609ms,一个用了1900ms的时间。


#include  
#include 
#include 
using namespace std;

 
//int dir[8][2]={-1,2, -2,1, -2,-1, -1,-2, 1,-2, 2,-1, 2,1, 1,2}; //这个dir用1900ms的时间

int dir[8][2]={2,1,  1,2  ,-1,2   ,-2,1  ,-2,-1   ,-1,-2  ,  1,-2,  2,-1};// 这个dir 用609ms的时间
int n;
int lim;
char rrr[70];
int ccc[70];
int vis[10][10];
int flag;
int ok(int x,int y)
{
	if(x>=1&&x<=n&&y>=1&&y<=n&&vis[x][y]==0)
		return 1;
	return 0;
} 



int dfs(int x,int y,int num)
{
	if(n*n==num)
		return flag=num;
	for(int i=0;i<8;i++)
	{
		int xx=dir[i][0]+x;
		int yy=dir[i][1]+y;
		if(ok(xx,yy))
		{
			rrr[lim]=xx+'a'-1;
			ccc[lim++]=yy;
			vis[xx][yy]=1;
			dfs(xx,yy,num+1);
			if(flag)
				return flag;
			vis[xx][yy]=0;
			lim--;

		}
	}
	return 0;
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	//for(n=1;n<=8;n++)
	{ 
		memset(vis,0,sizeof vis); 
		lim=0;
		flag=0;
		vis[1][1]=1;
		
		rrr[lim]='a';
		ccc[lim++]=1;
		dfs(1,1,1); 

		if(flag)
		{
			for(int i=0;i






你可能感兴趣的:(搜索)