POJ 2488 A Knight's Journey DFS

本文探讨了如何使用回溯算法解决国际象棋骑士遍历问题,确保每一步都符合规则且覆盖所有格子,实现路径字典序最小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出一个国际象棋的棋盘(行为字母,列为数字,如:A1)。判断骑士(类似于马)能否不重复的走遍棋盘上的每一个点。若有多种方式,输出字典序最小的。
题解:


#include <iostream>
using namespace std;

bool check[30][30];
int p,q,counter;
int dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2},{1, -2}, {1, 2}, {2, -1}, {2, 1}};

struct
{
	int a,b;
} path[900];

bool isOk ( int x, int y )
{
	if ( x < 1 || x > q || y < 1 || y > p || check[x][y] )
		return false;
	return true;
}

bool dfs ( int x, int y )
{
	check[x][y] = true;
	counter++;
	path[counter].a = x;
	path[counter].b = y;
	if ( counter == p*q )
		return true;
	int a,b;
	for ( int i = 0; i < 8; i++ )
	{
		a = x + dir[i][0];
		b = y + dir[i][1];
		if ( isOk(a,b) )
		{
			if ( dfs(a,b) )
				return true;
			check[a][b] = false;
			counter--;
		}
	}
	return false;
}

int main()
{
	int t;
	cin >> t;
	for ( int i = 1; i <= t; i++ )
	{
		cin >> p >> q;
		counter = 0;
		memset(check,0,sizeof(check));
		memset(path,0,sizeof(path));
		cout << "Scenario #" << i << ":" << endl;
		if ( dfs(1,1) )
		{
			for ( int j = 1; j <= p*q; j++ )
				cout << char(path[j].a + 'A' - 1 ) << path[j].b;
			cout << "\n\n";
		}
		else
			cout << "impossible" << "\n\n";
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值