poj 2488 A Knight…

来源:互联网 发布:匹配声音软件是什么 编辑:程序博客网 时间:2024/05/19 16:05
题意:骑士遍历,在一个p*q的棋盘中,求一条路径遍历完所有的格子,输出其路径(按字典序)。

思路:如果能,那必定是从A1这个格子出发(这应该很容易想明白) 一个难点就是要按字典序输出,只要控制搜索的方向就可以了即按字符小的搜索,字符相同的按数字小的搜索。然后就是DFS了。我定义 行为x,列为y(个人习惯)


//168K   16MS

#include
#include
const int MAX = 27;
int mat[MAX][MAX];
int dir[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};//字典序搜索的方向
char path[MAX*MAX][2];记录路径
int p,q;
bool flag;

void DFS(int x,int y,int dep)
{
    inti,x0,y0;
    if (dep ==q*p)
    {
       for (i = 0;i < q*p;i ++)
           printf ("%c%c",path[i][1],path[i][0]);
       printf ("\n");
       flag = true;
       return ;
    }
    for (i = 0;i< 8&&!flag;i ++)
    {
       x0 = x + dir[i][0];
       y0 = y + dir[i][1];
       if (x0<1||x0>p||y0<1||y0>q||mat[x0][y0])
           continue;
       mat[x0][y0] = 1;
       path[dep][0] = x0+'0';
       path[dep][1] = y0+'A'-1;
       DFS(x0,y0,dep+1);
       mat[x0][y0] = 0;
    }
    return;
}
int main ()
{
    intn,i,cnt;
    cnt =0;
    while(~scanf("%d",&n))
    {
       while (n --)
       {
           scanf ("%d%d",&p,&q);
           flag = false;
           printf ("Scenario #%d:\n",++cnt);
           memset (mat,0,sizeof(mat));
           path[0][0] = '1';
           path[0][1] = 'A';
           mat[1][1] = 1;
           DFS(1,1,1);
           if (!flag)
               printf ("impossible\n");
           printf ("\n");
       }
    }
    return0;
}

原创粉丝点击