poj 2488 A Knight's Journey

来源:互联网 发布:parsley.js 手册 编辑:程序博客网 时间:2024/06/12 23:29

首先要清楚棋盘行列表示方法。

注意要求按字典序输出,我的搜索方向是 dx[ ],dy[ ].

dfs初步,具体看代码。

<span style="font-size:14px;">#include <iostream>#include<stdio.h>#include<cstring>using namespace std;int visit[10][10];struct Step{    int x,y;};Step step[100];int p,q;  //p是行(数字),q是列(字母)int dx[8]={-1,1,-2,2,-2,2,-1,1};  //要满足字典序,顺序不能改int dy[8]={-2,-2,-1,-1,1,1,2,2};bool dfs(int i,int j,int no){      visit[i][j] = 1;      step[no].x = i;      step[no].y = j;      if(no == p*q)       return true;    for(int k =0;k < 8;k++)    {        int xx = i + dx[k];        int yy = j + dy[k];        if(xx > 0 && xx <= p && yy > 0 && yy <=q && !visit[xx][yy])            if(dfs(xx,yy,no+1)) return true;  //如果满足就跳出递归    }          visit[i][j] = 0;  //如果到了这一步,说明没有满足情况的          return false;    //此步骤记录归0,返回上一步}int main(){   int n;   scanf("%d",&n);   int count = 1;   while(n--)   {       bool ans = false;       memset(visit,0,sizeof(visit));       scanf("%d %d",&p,&q);       for(int j = 1;j <= q;j++)       {           for(int i = 1;i <= p;i++)           {               int no = 1; //no表示第几步               ans = dfs(i,j,no);               if(ans)                   break;           }           if(ans)              break;       }           printf("Scenario #%d:\n",count++);           if(ans)           {               for(int i =1;i <= p*q;i++)                   printf("%c%d",step[i].y + 'A' - 1,step[i].x);                   printf("\n");           }           else           printf("impossible\n");           printf("\n");   }    return 0;}</span>