您的位置:首页 > 其它

POJ 2488 A Knight's Journey 递归回溯题解

2014-08-03 16:38 483 查看
简单的递归回溯法,锻炼基本的编程能力。

这类题是对代码能力的要求比对思想的要求高点。

而且要审题,题目要求安lexicographically 顺序输出,不小心递归的顺序就会输出错误了。

棋盘是由数字列或者行,和字母列或者行组成的,故此输出结果要注意。

个人觉得我的递归回溯写法是非常清晰, 工整的,O(∩_∩)O哈哈~

#include <stdio.h>
#include <string.h>
const int MAX_N = 27;
bool board[MAX_N][MAX_N];
int res[MAX_N*MAX_N];
int row, col, total, id;

inline bool isLegal(int r, int c)
{
	return 0<=r && 0<=c && r<row && c<col && !board[r][c];
}

bool getTourPath(int r = 0, int c = 0, int n = 0)//r为字母, c为数字
{
	if (n == total) return true;
	if (!isLegal(r, c)) return false;
	res[id] = r, res[id+1] = c;//record result
	board[r][c] = true;//mark
	++++id, ++n;
	if (getTourPath(r-2, c-1, n)) return true;
	if (getTourPath(r-2, c+1, n)) return true;
	if (getTourPath(r-1, c-2, n)) return true;
	if (getTourPath(r-1, c+2, n)) return true;
	if (getTourPath(r+1, c-2, n)) return true;
	if (getTourPath(r+1, c+2, n)) return true;
	if (getTourPath(r+2, c-1, n)) return true;
	if (getTourPath(r+2, c+1, n)) return true;
	----id, --n;
	board[r][c] = false;//unmark
	return false;
}

int main()
{
	int T;
	scanf("%d", &T);
	for (int t = 1; t <= T; t++)
	{
		printf("Scenario #%d:\n", t);
		scanf("%d %d", &col, &row);
		memset(board, 0, sizeof(board));
		total = col*row;
		id = 0;
		if (getTourPath())
		{
			for (int i = 0; i < id; i += 2)
			{
				putchar(char(res[i]+'A'));
				putchar(char(res[i+1]+'1'));
			}
			putchar('\n');
		}
		else puts("impossible");
		putchar('\n');
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: