poj2488旧题重做标准DFS
注意:字典序。
其他没什么的了,主要是重新熟悉一下DFS的过程。。。久了就忘了。
#include<iostream>
#include<cstring>
using namespace std;
bool vis[25][25];
bool flag=0;
int p,q;
int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1}; // 字典序。
char path[50];
void DFS(int depth,int x,int y)
{
if(depth==p*q) //DFS首先是结束条件
{
flag=true;
return ;
}
for(int i=0;i<8&&flag==false;i++) //然后直接对每一步情况进行分析,这里flag算一个剪枝
{
int new_x=x+dx[i];
int new_y=y+dy[i]; //限制条件
if(new_x > 0 && new_y > 0 && new_x <= q && new_y <= p && vis[new_y][new_x] == false)
{//操作
vis[new_y][new_x]=true;
path[2*depth]=new_x+'A'-1;
path[2*depth+1]=new_y+'1'-1;
//递归
DFS(depth+1,new_x,new_y);
vis[new_y][new_x]=false;
}
}
}
void Init()
{
for(int y = 1; y <= p; y ++)
for(int x = 1; x <= q; x ++)
vis[y][x] = false;
flag=false;
vis[1][1]=true;
path[0]='A';
path[1]='1';
}
int main()
{
int T,t;
cin>>T;
t=1;
while(t<=T)
{
cin>>p>>q;
Init();
DFS(1,1,1);
if(flag)
{
cout<<"Scenario #"<<t<<':'<<endl;
for(int i = 0; i < 2 * p*q; i ++)
cout << path[i];
cout << endl << endl;
}
else
{
cout<<"Scenario #"<<t<<':'<<endl;
cout<<"impossible" << endl << endl;
}
t++;
}
return 0;
}

浙公网安备 33010602011771号