poj 2488 骑士游历

深度优先搜索与回溯结合进行

单纯的搜索与回溯的写法是不一样的,

回溯尤其是要记录搜索路径的时候,需要更多的处理

这题目感觉用数组,然后记录搜素深度来记录路径更好,还是用了双端队列,更麻烦了,调了一会

关键:如果DFS能达到,则从任何一点出发都能达到,所以以A1为起点,注意按照字典顺序

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <cctype>
#include <algorithm>
#include <cmath>
#include <deque>
#include <queue>
#include <map>
#include <queue>
#include <list>
#include <iomanip>
using namespace std;                                               
///
///
#define INF 0xffffff7
#define maxn 30
#define max(a,b)(a>b?a:b)
///
int color[maxn][maxn];//是否访问过
int p, q;
struct pos{
	int q;
	int p;
};
bool finish;
deque<pos> stk;//记录搜索路径
int dy[] = {-2, -2, -1, -1,  1, 1,  2, 2};
int dx[] = {-1,  1, -2,  2, -2, 2, -1, 1};
void dfs(int cur)
{
	int i, j;
	if ((cur == p * q) && !finish)
	{
		finish = true;
		while (!stk.empty())
		{
			pos tmpPos;
			tmpPos = stk.front();
			stk.pop_front();
			char temp = tmpPos.q + 'A';
			printf("%c%d", temp, tmpPos.p + 1);
		}
		printf("\n");
		return;
	}
	pos curpos = stk.back();
	for (i = 0; i < 8; i++)
	{
		pos newpos;
		newpos.q = curpos.q + dy[i];
		newpos.p = curpos.p + dx[i];
		if (newpos.q >= 0 && newpos.q < q && newpos.p >= 0 && newpos.p < p && color[newpos.q][newpos.p] == 0 && !finish)
		{
			color[newpos.q][newpos.p] = 1;
			stk.push_back(newpos);
			dfs(cur + 1);
			if (!finish)
				stk.pop_back();
			color[newpos.q][newpos.p] = 0;
		}
	}
}

int main()
{
	int i, j, k;
	int ncases;
	int cases = 1;
	scanf("%d", &ncases);
	while (ncases--)
	{
		scanf("%d %d", &p, &q);//q代表字母个数,p代表数字个数
		memset(color, 0, sizeof(color));
		finish = false;
		while (!stk.empty())
			stk.pop_back();
		printf("Scenario #%d:\n", cases);
		cases++;
		pos startpos;
		startpos.q = startpos.p = 0;
		color[startpos.q][startpos.p] = 1;
		stk.push_front(startpos);
		dfs(1);
		if (!finish)
			printf("impossible\n");
		printf("\n");
	}
	
	
	///
    return 0;
}                                              


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值