POJ2488 骑士旅行

3 篇文章 0 订阅
2 篇文章 0 订阅
#include<iostream>
#include<fstream>
#include<cstdlib>

using namespace std;

//#define DEBUG
/* 248K	0MS */
static	int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2};  /* 骑士只有8个位置可以移动 */
static	int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1};   // 字典序。 
static  int board[26][26];
static  int count;
static  int ok;
static  int p, q;
static	char path[26 * 2];
void search_dfs(int x, int y, int num)
{
	if (num >= count)
	{	
		ok = 1; 
		for (int i = 0; i < count * 2; i+=2)
			printf("%c%c", path[i], path[i + 1]);
		printf("\n");
	return;
	}
	if (1 == ok)	return;

	for (int i = 0; i < 8; i++)
	{
		int newx = x + dx[i];
		int newy = y + dy[i];
		if (newx >= q || newx < 0 || newy >= p || newy < 0 ||	board[newx][newy] == 1)	continue;

		board[newx][newy] = 1;
		path[num * 2] = 'A' + newx;	path[num * 2 + 1] = '1' + newy;
		search_dfs(newx, newy, num + 1);
		board[newx][newy] = 0;
		//path[num * 2] = 0;	path[num * 2 + 1] = 0;  /* ????*/

	}
}

int main()
{
#ifdef DEBUG
	fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif
	int t;
	cin >> t;
	for (int s = 1; s <= t; s++)
	{
		cin >> p >> q;
		int i, j;
		for (i = 0; i < p; i++)
			for (j = 0; j < q; j++)
				board[i][j] = 0;

		printf("Scenario #%d:\n", s);
		board[0][0] = 1; count = p * q;	ok = 0;
		path[0] = 'A'; path[1] = '1';
		search_dfs(0, 0, 1);
		if (0 == ok)
			printf("impossible\n");
		printf("\n");

	}
	return 0;
}

问题链接 POJ 2488   对于递归的过程需要认真思考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值