POJ 2488 A Knight's Journey
2016-05-18 12:39
295 查看
POJ 2488 A Knight’s Journey
[★★☆☆☆]搜索 深度优先
题目大意:
给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。样例
输入:3
1 1
2 3
4 3
输出:
Scenario #1:
A1
Scenario #2:
impossible
Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
解题思路:
水题,根据字典序dfs就行了。代码
#include <iostream> #include <algorithm> using namespace std; int h, l; bool used[30][30]; struct point{ int x, y; }; point ps[30]; int ctp; int dfs(int x, int y) { if (x-2 >= 1 && y-1 >= 1 && !used[x-2][y-1]) { used[x-2][y-1] = 1; point tp = {x-2, y-1}; ps[ctp++] = tp; if(dfs(x-2, y-1)) return 1; ctp--; used[x-2][y-1] = 0; } if (x-2 >= 1 && y+1 <= l && !used[x-2][y+1]) { used[x-2][y+1] = 1; point tp = {x-2, y+1}; ps[ctp++] = tp; if(dfs(x-2, y+1)) return 1; ctp--; used[x-2][y+1] = 0; } if (x-1 >= 1 && y-2 >= 1 && !used[x-1][y-2]) { used[x-1][y-2] = 1; point tp = {x-1, y-2}; ps[ctp++] = tp; if(dfs(x-1, y-2)) return 1; ctp--; used[x-1][y-2] = 0; } if (x-1 >= 1 && y+2 <= l && !used[x-1][y+2]) { used[x-1][y+2] = 1; point tp = {x-1, y+2}; ps[ctp++] = tp; if(dfs(x-1, y+2)) return 1; ctp--; used[x-1][y+2] = 0; } if (x+1 <= h && y-2 >= 1 && !used[x+1][y-2]) { used[x+1][y-2] = 1; point tp = {x+1, y-2}; ps[ctp++] = tp; if(dfs(x+1, y-2)) return 1; ctp--; used[x+1][y-2] = 0; } if (x+1 <= h && y+2 <= l && !used[x+1][y+2]) { used[x+1][y+2] = 1; point tp = {x+1, y+2}; ps[ctp++] = tp; if(dfs(x+1, y+2)) return 1; ctp--; used[x+1][y+2] = 0; } if (x+2 <= h && y-1 >= 1 && !used[x+2][y-1]) { used[x+2][y-1] = 1; point tp = {x+2, y-1}; ps[ctp++] = tp; if(dfs(x+2, y-1)) return 1; ctp--; used[x+2][y-1] = 0; } if (x+2 <= h && y+1 <= l && !used[x+2][y+1]) { used[x+2][y+1] = 1; point tp = {x+2, y+1}; ps[ctp++] = tp; if (dfs(x+2, y+1)) return 1; ctp--; used[x+2][y+1] = 0; } if (ctp == l*h) { for (int i = 0; i < ctp; i+ af4d +) { char c = ps[i].x + 'A' - 1; int d = ps[i].y; cout << c << d; } cout << endl; return 1; } return 0; } int main() { int TT; int ct = 1; cin >> TT; while (TT--) { cin >> l >> h; ctp = 0; for (int i = 0; i < 30; i++) { for (int j = 0; j < 30; j++) { used[i][j] = 0; } } used[1][1] = 1; point tp = {1,1}; ps[ctp++] = tp; cout << "Scenario #" << ct++ << ":" << endl; if(!dfs(1, 1)) cout << "impossible" << endl; cout << endl; } return 0; }
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2159 Ancient Cipher
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- POJ1050 最大子矩阵和
- 用单调栈解决最大连续矩形面积问题
- 2632 Crashing Robots的解决方法
- 1573 Robot Motion (简单题)