DFS basic problem, the main idea is to give the board size, ask the horse can travel all the lattice.
It is important to note that the topic requires the output path in dictionary order, so when traversing, you should follow the order from top to bottom and then from left to right. Here we begin to reverse up and down the order. Always WA.. is still too young. Some of the details of the code are ugly, which is probably the case.
#include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std;
int a[40][40];
int p,q;
int row[40],col[40],step=0;
int xr[]={-1,1,-2,2,-2,2,-1,1};
int yr[]={-2,-2,-1,-1,1,1,2,2}; void Dfs (int x,int y) {if (x<1 | | x>p | | y<1 | | y>q) return; Recursive boundary if (a[x][y]== 1) return;
Recursive boundary row[++step]=x;
Col[step]=y;
A[x][y]=1;
for (int i=0;i<8;i++) {int xx=x+xr[i];
int yy=y+yr[i];
DFS (XX,YY);
} if (step==p*q) return;
a[x][y]=0;
step--;
} int main () {//Freopen ("In.txt", "R", stdin);
int n;
scanf ("%d", &n);
for (int i=1;i<=n;i++) {scanf ("%d%d", &p,&q);
for (int j=1;j<=q;j++) {for (int k=1;k<=p;k++) {///Note the order of the Rows memset (A,0,sizeof (a));
Step=0;
DFS (K,J);
if (step==p*q) break;
} if (step==p*q) break;
} printf ("Scenario #%d:\n", i);
if (step==p*q) {for (int j=1;j<=step;j++) printf ("%c%d", col[j]+ ' A ' -1,row[j]);
printf ("\ n");
} else printf ("impossible\n\n");
} return 0;
}