`

POJ_2488_A Knight's Journey

阅读更多
http://poj.org/problem?id=2488

题意:经典的跳马问题【跳的方式当然就是中国象棋的方式了】。一个p*q的棋盘,从一个点开始,问有没有这样一种跳的方法,使得每次马经过的地方都不同并且能够跳完整个棋盘的点?

注意:方法有多种,要输出字典序最小的答案


#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <string>
#include <set>
#include <utility>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <ctype.h>
using namespace std;

int x_move[8] = {-2, -2, -1, -1, 1, 1, 2, 2};    //优先向字典序小的方向搜索,有点贪心,呵呵
int y_move[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
bool Map[30][30], flag;
int r, c;
char res[100];
void dfs (int x, int y, int step, int k)
{
	if (flag)
		return ;
	res[k] = x + 'A', res[k+1] = y + '1';    //记录路径
	if (step == r * c)    //走完全部格子,说明成功
	{
		flag = true;
		return ;
	}
	int i, tx, ty;
	for (i = 0; i < 8; i++)
	{
		tx = x + x_move[i];
		ty = y + y_move[i];
		if (tx >= 0 && ty >= 0 && tx < r && ty < c)
		{
			if (!Map[tx][ty])
			{
				Map[tx][ty] = true;
				dfs (tx, ty, step+1, k+2);
				Map[tx][ty] = false;
			}
		}
	}
}

int main()
{
	int t, k = 1;
	cin >> t;
	while (t--)
	{
		cin >> c >> r;
		memset (Map, false, sizeof(Map));
		Map[0][0] = true;
		flag = false;
		dfs (0, 0, 1, 0);
		cout << "Scenario #" << k++ << ":\n";
		if (!flag)
			cout << "impossible\n";
		else
		{
			res[2*r*c] = 0;    //封好字符串
			cout << res << endl;
		}
		cout << endl;
	}
	return 0;
}
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics