poj 2488

题目大意:给出一张地图从任意位置出发,找到一条路径,能够周游所有的地方。

解决:dfs+回溯,这道题更深刻理解了一下回溯,但是仍然不知道,遍历的顺序为何是这样,如果谁知道,请指教

也提供了一种记录路径的方法,进入递归函数立刻记录,因为这个x,y是有效的,只有进入递归的x,y才是有效的路径 

 

 

#include <iostream>
#include <bitset>
using namespace std;
int m,n;
int dx[]={-1,1,-2,2,-2,2,-1,1,};
int dy[]={-2,-2,-1,-1,1,1,2,2};
char res[900];
bool found;
bitset<30> b;

void tryIt(int p,int x,int y,int cnt)
{//可以这样理解,若进入循环,表明在x,y这个地方一定是可行的,那么我可以立刻将这一点进入res
    res[p]=y+'A';
    res[p+1]=x+'1';
    if(cnt==m*n){res[p+2]='\0';found=true;} 
 //   cout<<"this  step is:"<<res[p]<<"  "<<res[p+1]<<endl; 
//    show();system("pause");
    if(found)return;
    for(int i=0;i<8;i++)
    {
        int nx=x+dx[i];
        int ny=y+dy[i];
        if(nx>=0 && nx<m && ny >=0 && ny<n && b[nx*n+ny]==0)
        {
            b[nx*n+ny]=1;
            tryIt(p+2,nx,ny,cnt+1);//若判断出found了,就return
            if(found)return;
            b[nx*n+ny]=0;
        }
    }
}
int main()
{
    int icase;
    cin>>icase;
    for(int k=1;k<=icase;k++)
    {
        cin>>m>>n;
        found=false;
        for(int i=0;i<m && !found;i++)
         for(int j=0;j<n && !found;j++)
         {  
            b.reset();
            found=false; 
           //起始点标记,必不可少
            b[i*n+j]=1;   
            tryIt(0,i,j,1);
         }
         cout<<"Scenario #"<<k<<":"<<endl;
         if(found)cout<<res<<endl;
         else cout<<"impossible"<<endl;
         cout<<endl;
    }
    system("pause");
    return 0;
}
posted on 2011-09-06 21:44  猿类的进化史  阅读(455)  评论(0编辑  收藏  举报