| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 28697 | Accepted: 9822 |
Description
Background Input
Output
Sample Input
3 1 1 2 3 4 3
Sample Output
Scenario #1: A1 Scenario #2: impossible Scenario #3: A1B3C1A2B4C2A3B1C3A4B2C4
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <cstring>
using namespace std;
const int MAX = 9;
const int dirx[8]={-1,1,-2,2,-2,2,-1,1},diry[8]={-2,-2,-1,-1,1,1,2,2};
typedef struct Point{
int x,y;
}point;
int p,q,n;
bool visit[MAX][MAX];
point pre[MAX][MAX];
bool mark;
stack<int> stx,sty;
void printPath(int x,int y){
stx.push(x);
sty.push(y);
int tx,ty;
tx = pre[x][y].x;
ty = pre[x][y].y;
while(tx!=-1){
stx.push(tx);
sty.push(ty);
x = pre[tx][ty].x;
y = pre[tx][ty].y;
tx = x;
ty = y;
}
while(!stx.empty()){
printf("%c%d",sty.top()-1+‘A‘,stx.top());
stx.pop();
sty.pop();
}
printf("\n\n");
}
void dfs(int x,int y,int len){
if(mark)return;
if(len==p*q){
printPath(x,y);
mark = true;
return;
}
int i,tx,ty;
for(i=0;i<8;++i){
tx = x+dirx[i];
ty = y+diry[i];
if(tx<1 || tx>p || ty<1 || ty>q)continue;
if(visit[tx][ty])continue;
pre[tx][ty].x = x;
pre[tx][ty].y = y;
visit[tx][ty] = true;
dfs(tx,ty,len+1);
visit[tx][ty] = false;
}
}
int main()
{
//freopen("in.txt","r",stdin);
//(Author : CSDN iaccepted)
int i;
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Scenario #%d:\n",i);
scanf("%d %d",&p,&q);
memset(visit,0,sizeof(visit));
mark = false;
pre[1][1].x = -1;
pre[1][1].y = -1;
visit[1][1] = true;
dfs(1,1,1);
visit[1][1] = false;
if(!mark){
printf("impossible\n\n");
}
}
return 0;
}
思路就是DFS 搜下去,当走过的格子数达到格子总数时就打印路径。所以要用一个数组记录每个定点的前驱节点。
pku 2488 A Knight's Journey (搜索 DFS),布布扣,bubuko.com
pku 2488 A Knight's Journey (搜索 DFS)
原文地址:http://blog.csdn.net/iaccepted/article/details/26341633