DFS。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 101;
int v[SIZE][SIZE];
int path[SIZE];
int p, q, flag;
const int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
const int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
//字典序,从上至下,从左至右。
int check(int r, int c)
{
if(r >= 0 && c >= 0 && r < p && c < q)
return 1;
return 0;
}
void dfs(int x, int y, int step)
{
v[x][y] = 1;
path[step] = x*q+y;
if(step == p*q-1)
{
flag = 1;
for(int i = 0; i <= step; i++)
{
printf("%c%d", 'A'+path[i]%q, path[i]/q+1);
}
printf("\n");
return;
}
for(int i = 0; i < 8 && !flag; i++)
{
int xx = x+dx[i];
int yy = y+dy[i];
if(check(xx, yy) && !v[xx][yy])
{
dfs(xx, yy, step+1); //不可用++step,因为要保存路径。
}
}
v[x][y] = 0;
}
int main()
{
int T, times = 0;
scanf("%d", &T);
while(T--)
{
memset(v, 0, sizeof(v));
memset(path, 0, sizeof(path));
flag = 0;
v[0][0] = 1;
scanf("%d%d", &p, &q);
printf("Scenario #%d:\n", ++times);
dfs(0, 0, 0);
if(!flag)
{
printf("impossible\n");
}
printf("\n");
}
}
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 101;
int v[SIZE][SIZE];
int path[SIZE];
int p, q, flag;
const int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
const int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
//字典序,从上至下,从左至右。
int check(int r, int c)
{
if(r >= 0 && c >= 0 && r < p && c < q)
return 1;
return 0;
}
void dfs(int x, int y, int step)
{
v[x][y] = 1;
path[step] = x*q+y;
if(step == p*q-1)
{
flag = 1;
for(int i = 0; i <= step; i++)
{
printf("%c%d", 'A'+path[i]%q, path[i]/q+1);
}
printf("\n");
return;
}
for(int i = 0; i < 8 && !flag; i++)
{
int xx = x+dx[i];
int yy = y+dy[i];
if(check(xx, yy) && !v[xx][yy])
{
dfs(xx, yy, step+1); //不可用++step,因为要保存路径。
}
}
v[x][y] = 0;
}
int main()
{
int T, times = 0;
scanf("%d", &T);
while(T--)
{
memset(v, 0, sizeof(v));
memset(path, 0, sizeof(path));
flag = 0;
v[0][0] = 1;
scanf("%d%d", &p, &q);
printf("Scenario #%d:\n", ++times);
dfs(0, 0, 0);
if(!flag)
{
printf("impossible\n");
}
printf("\n");
}
}