您的位置:首页 > 其它

POJ 2488 搜索题DFS

2012-09-01 15:11 281 查看
题目链接

题目大意是说:给你起个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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: