POJ 2488 A Knight's Journey

题目链接: http://poj.org/problem?id=2488

被字典序弄疯了,干脆枚举所有情况,然后找个字典序最小的吧。。不过代码还是很短的。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 struct Point
 5 {
 6     int x, y;
 7 };
 8 
 9 int map[30][30], n, m;
10 const int dir[8][2] = {{-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}};
11 bool vis[30][30];
12 char path[60], ans[60];
13 
14 void dfs(int x, int y, int cnt)
15 {
16     vis[x][y] = 1;
17     path[cnt++] = y + 'A' - 1;
18     path[cnt++] = x + '0';
19     if(cnt / 2 == n*m)
20     {
21         path[cnt] = 0;
22         if(ans[0] == 0 || strcmp(path, ans) < 0)
23             strcpy(ans, path);
24     }
25     for(int i = 0; i < 8; i++)
26     {
27         int nx = x + dir[i][0];
28         int ny = y + dir[i][1];
29         if(nx > 0 && nx <= n && ny > 0 && ny <= m && !vis[nx][ny])
30             dfs(nx, ny, cnt);
31     }
32     vis[x][y] = 0;
33 }
34 
35 int main()
36 {
37     int t;
38     scanf("%d", &t);
39     for(int i = 1; i <= t; i++)
40     {
41         scanf("%d %d", &n, &m);
42         printf("Scenario #%d:\n", i);
43         memset(vis, 0, sizeof(vis));
44         ans[0] = 0;
45         dfs(1, 1, 0);
46         if(ans[0] == 0)
47             printf("impossible\n\n");
48         else
49             printf("%s\n\n", ans);
50     }
51     return 0;
52 }
View Code

 

posted @ 2013-08-14 11:06  Anti-Magic  阅读(211)  评论(0编辑  收藏  举报