[DFS]poj2488

http://poj.org/problem?id=2488

这道题不是很容易的。

1.字典序(不知道原因知道怎么弄)程序里面的1、2什么的就是保证字典序的搜索方法。

2.深搜,记录径,我的想法和别人不一样,我是记录每个点的上一个点,而且写法有一点点的特别。

我写深搜喜欢先派生节点然后每个节点判断是否满足条件,而不是像其他人那样,先判断满不满足条件,然后再派生节点。。

3.递归倒着输出路径(make函数)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#define rep(i,n,m) for(int i=(n);i<=(m);++i)
#define re1(i,n) rep(i,1,n)
#define re0(i,n) rep(i,0,n)
#define RE(a) ((a)*(a))
using namespace std;
const int maxnum=26+1;
int mapp[maxnum][maxnum];
struct node{
	int x,y;
	node(){
		
	}
	node(int x,int y):x(x),y(y){

	}
}way[maxnum][maxnum];
int dir[8][2]={
-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1//for dictionary order
};
int p,q;
bool is_overflow(int x,int y){
	if(x<=0 || y<=0)
		return true;
	if(x>p || y>q)
		return true;
	return false;
}
int c,ans1,ans2,flag;
bool solve(int i,int j,int c){
	if(is_overflow(i,j) || mapp[i][j])
		return false;
     if(flag)
        return ture; mapp[i][j]=1; if(c==p*q-1){ ans1=i; ans2=j; flag=true; return true; } re0(u,7){ int xx=i+dir[u][0]; int yy=j+dir[u][1]; if(solve(xx,yy,c+1)){ way[xx][yy].x=i; way[xx][yy].y=j; return true; } } mapp[i][j]=0; return false; } void make(int i,int j){ if(i==j && j==-1) return; make(way[i][j].x,way[i][j].y); printf("%c%d",char(i+'A'-1),j); } int main(){ int tcase,tnum=0; scanf("%d",&tcase); while(tcase--){ scanf("%d%d",&q,&p); re1(u,p)re1(w,q){ way[u][w].x=way[u][w].y=-1; mapp[u][w]=0; } printf("Scenario #%d:\n",++tnum); flag=false; if(solve(1,1,0)){ make(ans1,ans2); puts(""); }else printf("impossible\n"); puts(""); } }

  

posted @ 2012-12-18 19:08  GGGin  阅读(142)  评论(0编辑  收藏  举报