您的位置:首页 > 其它

pku 2488 A Knight's Journey DFS

2009-12-06 00:06 211 查看
经典DFS.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int dx[] = {-1, 1, -2, 2, -2, 2, -1, 1};
int dy[] = {-2, -2, -1, -1, 1, 1, 2, 2};

bool visited[9][9];
int path1[64], path2[64];
int width, height;
bool bOk;

inline bool ok(int x, int y, int dx, int dy)
{
if(x+dx<1 || x+dx>width || y+dy<1 || y+dy>height)
return false;
return true;
}

void dfs(int x, int y, int n)
{
if(n == width*height-1)
{
bOk = true;
return;
}

for(int i = 0; !bOk && i < 8; ++i)
if(ok(x, y, dx[i], dy[i]) && !visited[x+dx[i]][y+dy[i]])
{
visited[x+dx[i]][y+dy[i]] = true;
path1
= x+dx[i], path2
= y+dy[i];
dfs(x+dx[i], y+dy[i], n+1);
visited[x+dx[i]][y+dy[i]] = false;
}
}

int main()
{
int cnt;
scanf("%d", &cnt);
for(int n = 1; n <= cnt; ++n)
{
scanf("%d%d", &width, &height);

printf("Scenario #%d:/n", n);
if(width == 1 && height == 1)
{
printf("A1/n/n");
continue;
}

memset(visited, 0, sizeof(visited));
memset(path1, 0, sizeof(path1));
memset(path2, 0, sizeof(path2));

bOk = false;
visited[1][1] = true;
dfs(1, 1, 0);

if(bOk)
{
printf("A1");
for(int i = 0; i < width*height-1; ++i)
printf("%c%d", path2[i]+'A'-1, path1[i]);
printf("/n/n");
}
else
printf("impossible/n/n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: