题目大意
给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。
注意
有两点注意:
1:路径需要按字典序输出
2:每组数据末尾有一行空行
代码
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<stack>
using namespace std;
const int INF=999999999;
int T;
int p,q;//p是行数q是列数
int mat[10][10];
int bj[10][10];
int sum=0;
int xx[9]={0,-2,-2,-1,-1,1,1,2,2};
int yy[9]={0,-1,1,-2,2,-2,2,-1,1};
bool Is_Can(int x,int y)
{
if(x<=q && x>=1 && y<=p && y>=1)return 1;
else return 0;
}
struct Node
{
int x;
int y;
Node()
{
x=x;y=y;
}
Node(int i,int j)
{
x=i;y=j;
}
};
stack<Node> st;
stack<Node>st2;
int Dfs(int x,int y)//x y已被标记
{
if(sum==q*p)return 1;
int tx,ty;
for(int i=1;i<=8;i++)
{
tx=x+xx[i];
ty=y+yy[i];
if(Is_Can(tx,ty) && bj[tx][ty]==0)
{
bj[tx][ty]=1;
sum++;
st.push(Node(tx,ty));
if(sum==q*p)return 1;
Dfs(tx,ty);
if(sum==q*p)return 1;
st.pop();
sum--;
bj[tx][ty]=0;
}
}
return -1;
}
int main()
{
int Case=0;
cin>>T;
int t;
while(T--)
{
sum=0;
Node temp;
memset(bj,0,sizeof(bj));
memset(mat,0,sizeof(mat));
while(!st.empty())st.pop();
while(!st2.empty())st2.pop();
cin>>p>>q;
bj[1][1]=1;
st.push(Node(1,1));
sum++;
t=Dfs(1,1);
printf("Scenario #%d:\n",++Case);
if(t!=-1)
{
while(!st.empty())
{
st2.push(st.top());
st.pop();
}
while(!st2.empty())
{
temp=st2.top();
st2.pop();
cout<<(char)(temp.x-1+(int)'A')<<temp.y;
}
cout<<endl;
}
else printf("impossible\n");
cout<<endl;
}
}
808

被折叠的 条评论
为什么被折叠?



