您的位置:首页 > 其它

典型地图搜索 pku 2488 A Knight's Journey

2010-08-26 01:02 435 查看
题目:

http://acm.pku.edu.cn/JudgeOnline/problem?id=2488



#include <stdio.h>
#include <memory>

#define max 27

struct Step{
	char x;
	int y;
}steps[max * max];

//int dir[8][2] = {{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
int dir[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
int map[max][max];

int row,col;

bool inside(int i,int j){
	if(1 <= i && i <= row && j >= 1 && j <= col)
		return true;
	return false;
}

bool dfs(int i,int j,int count){
	//当前在第i行,j列格子.
	//从该格子出发,访问下一个格子
	//直到所有的格子都已经走过的时候.
	//或者有些格子不能访问.函数结束.
	steps[count].x = 'A' + i - 1;
	steps[count].y = j;
	if(count == row * col)
		return true;
	for(int k = 0;k < 8;k++){
		int nr = i + dir[k][0];
		int nc = j + dir[k][1];
		if(inside(nr,nc) && !map[nr][nc]){
			map[nr][nc] = 1;
			//从nr,nc位置继续深度优先访问棋盘
			if(dfs(nr,nc,count + 1))
				return true;
			//回溯
			map[nr][nc] = 0;
		}
	}
	return false;
}

int main(){
	int t;
	//FILE *fp = fopen("data.txt","r");
	scanf("%d",&t);
	//fscanf(fp,"%d",&t);
	for(int i = 1;i <= t;i++){
		scanf("%d%d",&col,&row);
		//fscanf(fp,"%d%d",&col,&row);
		memset(map,0,sizeof(map));
		memset(steps,0,sizeof(steps)/sizeof(Step));
		printf("Scenario #%d:/n",i);
		map[1][1] = 1;
		if(dfs(1,1,1)){
			for(int j = 1;j <= row * col;j++)
				printf("%c%d",steps[j].x,steps[j].y);
			printf("/n/n");
		}
		else
			printf("impossible/n/n");
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: