poj2488

简单跳马搜索

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
using namespace std;

#define maxn 26

struct Point
{
int x, y;
} way[maxn
* maxn];

bool map[maxn][maxn];
int p, q;
bool found;
int dir[8][2] =
{
{
-2, -1 },
{
-2, 1 },
{
-1, -2 },
{
-1, 2 },
{
1, -2 },
{
1, 2 },
{
2, -1 },
{
2, 1 } };

bool ok(int x, int y)
{
if (x < 0 || y < 0 || x >= q || y >= p)
return false;
if (map[x][y])
return false;
return true;
}

void dfs(int x, int y, int step)
{
way[step].x
= x;
way[step].y
= y;
if (step == p * q - 1)
{
found
= true;
return;
}
for (int i = 0; i < 8; i++)
if (ok(x + dir[i][0], y + dir[i][1]))
{
map[x
+ dir[i][0]][y + dir[i][1]] = true;
dfs(x
+ dir[i][0], y + dir[i][1], step + 1);
if (found)
return;
map[x
+ dir[i][0]][y + dir[i][1]] = false;
}
}

void print()
{
for (int i = 0; i < p * q; i++)
printf(
"%c%d", way[i].x + 'A', way[i].y + 1);
printf(
"\n\n");
}

int main()
{
//freopen("t.txt", "r", stdin);
int t;
scanf(
"%d", &t);
int s = 0;
while (t--)
{
s
++;
printf(
"Scenario #%d:\n", s);
memset(map,
0, sizeof(map));
scanf(
"%d%d", &p, &q);
for (int i = 0; i < q; i++)
{
for (int j = 0; j < p; j++)
{
found
= false;
map[i][j]
= true;
dfs(i, j,
0);
if (found)
break;
map[i][j]
= false;
}
if (found)
break;
}
if (found)
print();
else
printf(
"impossible\n\n");
}
return 0;
}

posted @ 2011-05-22 15:08  金海峰  阅读(739)  评论(0编辑  收藏  举报