POJ 2488 A Knight's Journey【DFS】
补个很久之前的题解。。。。
题目链接:
http://poj.org/problem?id=2488
题意:
马走“日”字,让你为他设计一条道路,走遍所有格,并输出字典序最小的一条。
分析:
dfs~~~
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int, int>pii;
const int maxn = 70;
pii pa[maxn],dr[10];
int v[maxn][maxn];
int r[8]={-1,1,-2, 2,-2,2,-1,1};
int d[8]={-2,-2,-1,-1,1, 1,2,2};
int n,p,q;
bool cmp(pii a, pii b)
{
if(a.first == b.first) return a.second < b.second;
else return a.first < b.first;
}
int dfs(int cnt, int a, int b)
{
pa[cnt++] = make_pair(a, b);
v[a][b]=1;
if(cnt == p*q){
for(int i = 0; i < cnt; i++)
cout<<(char)(pa[i].first+'A')<<pa[i].second+1;
cout<<endl<<endl;
return 1;
}
int k = 0, na, nb;
for(int i = 0; i < 8; i++){
na = a + d[i], nb = b+ r[i];
if(v[na][nb]==0&&0 <= na && na < q && 0 <= nb && nb < p){
if(dfs(cnt, na, nb)) return 1;
v[na][nb]=0;
}
}
v[a][b]=0;
return 0;
}
int main (void)
{
cin>>n;
for(int i = 0; i < n; i++){
memset(v, 0, sizeof(v));
cin>>p>>q;
cout<<"Scenario #"<<i+1<<":"<<endl;
if(!dfs(0, 0, 0)) cout<<"impossible"<<endl<<endl;
}
return 0;
}