紀念第一次AC的dfs題
阿新 • • 發佈:2021-02-04
poj 2488
#include <stdio.h>
#include <string.h>
int n, p, q, flag;
int a[8] = { -1,1,-2,2,-2,2,-1,1 };//先下後上,因為從(1,1)開始,先下後上能儘可能避免超過限值,進而達到儘量先左後右的目的。
int b[8] = { -2,-2,-1,-1,1,1,2,2 };
int book[10][10];
typedef struct {
char e;
char f;
}coordinate;
coordinate coor[ 26];
int k;
void dfs(int x, int y, int step)
{
int i;
int nx, ny;
coor[step].e = x + '0';
coor[step].f = y + 'A' - 1;
if (step == p * q)
{
flag = 1;
return;
}
for (i = 0; i < 8; i++)
{
nx = x + a[i];
ny = y + b[i];
if (nx < 1 || nx>p || ny<1 || ny>q)
continue;
if (book[nx][ny] == 0 && flag==0)
{
book[nx][ny] = 1;
dfs(nx, ny, step + 1);
book[nx][ny] = 0;
}
if (flag == 1)
return;
}
return;
}
int main()
{
int i;
while (scanf("%d", &n) != EOF)
{
for (k = 1; k <= n; k++)
{
memset(book, 0, sizeof(book));
scanf("%d%d", &p, &q);
flag = 0;
book[1][1] = 1;
dfs(1, 1, 1);
if (flag)
{
printf("Scenario #%d:\n", k);
for (i = 1; i <= p * q; i++)
{
printf("%c%c", coor[i].f, coor[i].e);
}
printf("\n\n");
}
else
printf("Scenario #%d:\nimpossible\n\n", k);
}
}
return 0;
}