URAL 1298. Knight(DFS)

题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1298


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


题意:

输出能跳完所有格子的路径!


代码如下:

#include 
#include 
int xx[8]= {2,1,-1,-2,-2,-1,1,2};
int yy[8]= {1,2,2,1,-1,-2,-2,-1};
int vis[17][17];
int n;
int judge(int x, int y)
{
    if((x>=1&&x<=n) && (y>=1&&y<=n) && !vis[x][y])
        return 1;
    return 0;
}
int dfs(int x, int y, int num)
{
    if(num == n*n)
        return 1;
    for(int i = 0; i < 8; i++)
    {
        int dx = x+xx[i];
        int dy = y+yy[i];
        if(judge(dx,dy))
        {
            vis[dx][dy] = num+1;
            if(dfs(dx,dy,num+1))
            {
                return 1;
            }
            vis[dx][dy] = 0;
        }
    }
    return 0;
}
int main()
{
    while(~scanf("%d",&n))
    {
        memset(vis,0,sizeof(vis));
        vis[1][1] = 1;
        if(n == 1)
        {
            printf("a1\n");
            continue;
        }
        if(n==2 || n==3 || n==4)
        {
            printf("IMPOSSIBLE\n");
            continue;
        }
        int flag = 0;
        flag = dfs(1,1,1);
        if(!flag)
        {
            printf("IMPOSSIBLE\n");
        }
        else
        {
            for(int k = 1; k <= n*n; k++)
            {
                for(int i = 1; i <= n; i++)
                {
                    for(int j = 1; j <= n; j++)
                    {
                        if(vis[i][j] == k)
                        {
                            printf("%c%d\n",i+'a'-1,j);
                        }
                    }
                }
            }
        }
    }
    return 0;
}


你可能感兴趣的:(DFS)