//poj2488 A knight's Journey
//给行数列数,求问能否遍历,给出字典序的一种遍历
//深度优先遍历dfs
#include<iostream>
#include<string>
using namespace std;
//visit[row][col] : 存储该点是否被访问过
bool visit[27][27];
//opt[8][2]:表示行走方向,用此来保证字典序
int opt[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
//output[27][2] 表示需要输出的路径
char output[27][2];
//flag :true表示找到了一种可能的遍历
bool flag;
int row,col;
void dfs(int x, int y, int dep)
{
if(dep == row * col)
{
flag = true;
return;
}
else
{
for(int i=0; i<8; i++)
{
int next_x = x + opt[i][0];
int next_y = y + opt[i][1];
if(next_x >=1 && next_x <= col && next_y >=1 && next_y <= row && !flag && !visit[next_x][next_y])
{
visit[next_x][next_y] = true;
output[dep][0] = next_x + 'A' - 1;
output[dep][1] = next_y + '0';
dfs(next_x,next_y,dep+1);
if(flag)
return;
visit[next_x][next_y] = false;
}
}
}
}
int main()
{
int n;
cin >> n;
for(int t=1; t<=n; t++)
{
memset(visit,0,sizeof(visit));
memset(output,0,sizeof(output));
cin >> row >> col;
flag = false;
output[0][0] = 'A';
output[0][1] = '1';
visit[1][1] = true;
dfs(1,1,1);
cout << "Scenario #" << t << ":" << endl;
if(flag)
{
for(int i=0; i<row*col; i++)
cout << output[i][0] << output[i][1];
}
else
cout << "impossible";
cout << endl << endl;
}
}
poj 2488——dfs深度优先遍历
最新推荐文章于 2020-05-03 12:07:40 发布