/*
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;
}
POJ2488 A Knight's Journey(DFS)
最新推荐文章于 2021-02-28 00:17:31 发布