POJ 2488 搜索题DFS

题目链接

题目大意是说:给你起个p*q的棋盘,然后让你用中国象棋的马去遍历棋盘,然后让你求出字典序最小的游历顺序。。这其实就是一个马的周游问题。

同样的也是搜索,多的不说了。

#include <iostream>

#include <cstdio>

#include <string>

#include <cstring>



using namespace std;



string res;  //保存答案

int f[30][30];    //这里千万别开小了,开始的时候我就是开小了然后wa了几次

int N;

int a,b;

int move[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};

int cnt;

int flag,k;





void DFS(int x,int y)   //x,y分别表示目前所在点的坐标,至于问什么从0,0开始搜索,一是题目要求字典序最小,二是贪心的原因,这点可以百度下

{

     if(cnt==a*b)

     {

                 flag=1;

                 cout<<res<<endl<<endl;

                 return;

     }

     if(flag==1)

                return ;

     

     for(int i=0;i<8;i++)

     {

             int nextx,nexty;

             nextx=x+move[i][0];

             nexty=y+move[i][1];

             if(!f[nextx][nexty] && nextx>=0 && nextx<a && nexty>=0 &&nexty<b )

             {

                                 f[nextx][nexty]=1;

                                 cnt++;

                                 res+=(char)('A'+nexty);

                                 res+=(char)('1'+nextx);

                                 DFS(nextx,nexty);

                                 f[nextx][nexty]=0;

                                 cnt--;

                                 res=res.substr(0,res.length()-2);      //这步回溯

             }

     }

}



int main(void)

{

    scanf("%d",&N);

    for(k=1;k<=N;k++)

    {

            scanf("%d%d",&a,&b);

            memset(f,0,sizeof(f));

            cnt=1;

            f[0][0]=1;

            flag=0;

            res="A1";

            printf("Scenario #%d:\n",k);

            DFS(0,0); 

            if(flag==0)

            {

                       printf("impossible\n\n");

            }

    }

    return 0;

}

你可能感兴趣的:(poj)