转载请注明出处
图的遍历算法---DFS(深度优先+递归+回退)
注意:1.书写DFS函数式,首先对该点进行标记chess[x][y]=true,并把位置用way[deep].row和way[deep].col记录,然后对该点所有可能的下一点进行遍历+回退
2.字典序,确保第一点为A1,对每点扫描的时候也按照字典的先后顺序进行di[8]和dj[8].
/********************Invented by Hacker_vision******************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e3+10;
bool chess[30][30];
bool flag;
int step;
int p,q;
int di[8]={-1,1,-2,2,-2,2,-1,1};
int dj[8]={-2,-2,-1,-1,1,1,2,2};//对字典序的理解要正确呦
struct node
{
int row;
char col;
}way[30];
void dfs(int x,int y,int deep)
{
chess[x][y]=true;
way[deep].row=x;way[deep].col='A'+y-1;//先标记再遍历
if(deep==step) {
flag=true;
return;
}
for(int i=0;i<8&&flag==false;i++){
int pos_x=x+di[i];
int pos_y=y+dj[i];
if(pos_x>=1&&pos_x<=p&&pos_y>=1&&pos_y<=q&&chess[pos_x][pos_y]==false){
dfs(pos_x,pos_y,deep+1);//向下遍历
chess[pos_x][pos_y]=false;//回退
}
}
return;
}
int main(void)
{
// freopen("input.txt","r",stdin);
int T;cin>>T;
int count=0;
while(T--){
cin>>p>>q;
cout<<"Scenario #"<<++count<<":"<<endl;
memset(chess,false,sizeof(chess));
step=p*q;
flag=false;
// way[1].row=1,way[1].col='A';
dfs(1,1,1);
if(flag==false) cout<<"impossible"<<endl<<endl;
else{
for(int i=1;i<=step;++i)
cout<<way[i].col<<way[i].row;
cout<<endl<<endl;
}
}
return 0;
}