POJ2488 A Knight's Journey(DFS)

25 篇文章 0 订阅
/*
1. dfs
2. typedef
	typedef 类型 别名; 
3. pair<int, int>
	【pair的定义】:
		例子1:pair<类型1, 类型2> 变量名;
		例子2(结合typedef):
			typedef pair<int, int> POS;
			POS po; 
	【pair类型的引用】:
		变量名.first = ...;    
		变量名.second = ...; 
	【pair的字面量形式】:
		例子1:pair<int, int>(1, 2)
		例子2(结合typedef使用):
			typedef pair<int, int> POS;
			POS(1, 1)  
4. vector的使用
	【导入库】:#include <vector>
	【定义】:vector<类型> 数组名;
	【引用】:数组名[index]
	【API】:
		vector<int> a;  // 声明一个vector数组a 
		a.size();  // 读取数组 a 的大小 
		a.resize(num); // 改变 a 的大小(a.resize(0)可以用来清空数组) 
		a.push_back(...);  // 在 a 的末尾添加元素 
		a.pop_back();  // 去掉 a 的末尾的元素 
*/

#include <iostream>
#include <vector>
using namespace std;

const int maxn = 100;
int markChessBoard[maxn][maxn] = {0};  // 1:走过  0:没走过 
int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};  
int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int p, q;
typedef pair<int, int> POS;
POS pos(1, 1);
vector<POS> positions;
bool flag = false; // 跳不了的flag

void dfsn(int x, int y, int count)
{
	if (flag == false)
	{
		int i;
		// 递归边界
		if (count >= p*q) 
		{
			// 输出显示 
			flag = true;
			for (i=0;i<positions.size();i++)
			{
				char temp = 'A' + positions[i].second - 1;
				cout<<temp<<positions[i].first;
			}
			cout<<endl;
			return;
		}
		 
		// 遍历8个方向的走法 
		for (i=0;i<8;i++)
		{
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (1 <= nx && nx <= p && 1 <= ny && ny <= q && markChessBoard[nx][ny] == 0)
			{
				markChessBoard[nx][ny] = 1;
				pos.first = nx;
				pos.second = ny;
				positions.push_back(pos);
				
				dfsn(nx, ny, ++count);
				
				count--;
				markChessBoard[nx][ny] = 0;
				positions.pop_back();
			}
		}		
	}
	else 
		return;
} 

int main() 
{
	int n, s = 0;
	cin>>n;
	while(n--)
	{
		int i,j;
		s = s + 1;
		cin>>p>>q;
		cout<<"Scenario #"<<s<<":"<<endl;
		// 一系列初始化 
		for (i=0;i<50;i++)
			for (j=0;j<50;j++)
			{
				markChessBoard[i][j] = 0;  // 初始化标记
			}
		markChessBoard[1][1] = 1;  // 以(A,1)为起点 
		positions.resize(0);  // 清空vector数组 
		positions.push_back(POS(1, 1)); // 把起点(1,1)加到vector数组中 
		flag = false;   // 初始化成功标记 
		// 开始进入dfs 
		dfsn(1, 1, 1);  // (起始行坐标,起始列坐标,计数变量) 
		if (!flag) 
		{
			cout<<"impossible"<<endl;
		}
		if (n != 0)
			cout<<endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值