POJ 2488 A Knight's Journey

  
    
/*
p 横
q 竖
顺序...
这题要按照字典序顺序搜索,深搜策略,判断成功的条件是走的步数等于格子的数目
*/

#include
< stdio.h >
#include
< string .h >
#define MAXN 27

int map[MAXN][MAXN];
int p, q, cas, ok, step;;
int pathX[MAXN], pathY[MAXN];
int dr[ 8 ][ 2 ] = {{ - 2 , - 1 }, { - 2 , 1 }, { - 1 , - 2 }, { - 1 , 2 },{ 1 , - 2 }, { 1 , 2 }, { 2 , - 1 }, { 2 , 1 }}; // 字典序顺序

int legal( int x, int y){
if (x <= 0 || y <= 0 || x > p || y > q)
return 0 ;
return 1 ;
}
void DFS( int x, int y){
if ( ok )
return ;
pathX[step]
= y;
pathY[step]
= x;
step
++ ;
if (step == p * q){
ok
= 1 ;
return ;
}
int d;
map[x][y]
= 1 ;
for (d = 0 ; d < 8 ; ++ d){
int newx = x + dr[d][ 1 ], newy = y + dr[d][ 0 ];
if (legal(newx, newy) && ! map[newx][newy] ){
DFS(newx, newy);
step
-- ;
}
}
map[x][y]
= 0 ;
}
void preProcess(){
printf(
" Scenario #%d:\n " , ++ cas);
memset(map,
0 , sizeof (map));
ok
= 0 ;
step
= 0 ;
}
void printPath(){
int i;
for (i = 0 ; i < p * q; ++ i){
printf(
" %c%d " ,pathX[i] + ' A ' - 1 , pathY[i]);
}
printf(
" \n " );
}
int main(){
int n, i;
scanf(
" %d " , & n);
for (i = 1 ; i <= n; ++ i){
preProcess();
scanf(
" %d %d " , & p, & q);
DFS(
1 , 1 );
if ( ok ){
printPath();
}
else {
printf(
" impossible\n " );
}
if (i != n)
printf(
" \n " );
}
return 0 ;
}

你可能感兴趣的:(poj)