POJ 2488 A Knight's Journey (DFS)

时间:2022-10-24 22:35:14
POJ 2488 A Knight's Journey (DFS)

poj-2488

题意:一个人要走遍一个不大于8*8的国际棋盘,他只能走日字,要输出一条字典序最小的路径
题解:
(1)题目上说的“The knight can start and end on any square of the board.”,是个坑点,其实要走字典序最小只需从A1开始遍历就行,因为从任意一点开始,只要能遍历完整个地图,那么A1也可以;
(2)要使字典序最小,那么遍历顺序一定要注意

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

(3)还有一个题上说1<=p*q<=26,那么如果p=1时,q=26时,所以数组要大于26;
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 100;
int vis[maxn][maxn],Map[2][maxn];
int n,m,N,ans;
int flag; int dr[8]={-1,1,-2,2,-2,2,-1,1};
int dc[8]={-2,-2,-1,-1,1,1,2,2}; bool judge(int x,int y){
if(x>=1&&x<=n&&y>=1&&y<=m&&vis[x][y]==0)return true;
else return false;
} void dfs(int x,int y,int st){
Map[0][st]=x;
Map[1][st]=y;//记录路径
if(st>=N){
flag=1;//满足条件标记
for(int i=1;i<=N;i++){
printf("%c%d",Map[1][i]-1+'A',Map[0][i]);
}cout<<endl;
return;
}
for(int i=0;i<8;i++){
int dx=x+dr[i];
int dy=y+dc[i];
if(judge(dx,dy)){
Map[0][st]=x;
Map[1][st]=y;
vis[dx][dy]=1;
dfs(dx,dy,st+1);
if(flag)return;//一旦找到一组解就返回,不再进行回溯
vis[dx][dy]=0;
}
}
} int main(){
int t;
while(cin>>t){
int cas=0;
while(t--){
cin>>n>>m;
memset(vis,0,sizeof(vis));
printf("Scenario #%d:\n",++cas);
flag=0;
N=n*m;
ans=0;
vis[1][1]=1;
dfs(1,1,1);
if(!flag)cout<<"impossible\n"<<endl;
else cout<<endl;
}
}
}