您的位置:首页 > 其它

poj 2488 A Knight's Journey(简单dfs)

2014-06-03 19:33 423 查看
http://poj.org/problem?id=2488

大致题意:给一个p*q的方格,p代表行数(1,2,3....),q代表列数(A,B,C....),要求输出骑士从任意一点出发经过所有点的路径,必须按字典序输出;路径不存在输出impossible示)。骑士可以一步到达他周围的八个格子(如题所示)

思路:基础的dfs,注意的是按字典序输出路径必须按dir[8][2]
= {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}的顺序;


而且起点必须是A1。


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <math.h>
#include <string.h>
#include <queue>
#include <string>
#define LL long long
#define _LL __int64
#define eps 1e-8

using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 26;
const int maxm = 1010;
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
int n,m;
int vis[maxn][maxn];
struct node
{
	int x;
	int y;
}ans[30];

bool dfs(int x, int y ,int step)
{
	vis[x][y] = 1;
	ans[step] = ((struct node){x,y});

	if(step == n*m)
		return true; //递归边界

	for(int d = 0; d < 8; d++)
	{
		int xx = x + dir[d][0];
		int yy = y + dir[d][1];
		if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy])
			if(dfs(xx,yy,step+1))
				return true;
	}
	vis[x][y] = 0; //走到这一步,说明(x,y)走不通,所以要重新标记为0
	return false;
}

int main()
{
	int test;
	scanf("%d",&test);

	for(int item = 1; item <= test; item++)
	{
		scanf("%d %d",&n,&m);

		memset(vis,0,sizeof(vis));

		printf("Scenario #%d:\n",item);

		if(dfs(1,1,1))
		{
			for(int i = 1; i <= n*m; i++)
				printf("%c%d",ans[i].y-1+'A',ans[i].x);
			printf("\n\n");
		}
		else printf("impossible\n\n");

	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: