POJ 2488 A Knight's Journey 递归回溯题解
2014-08-03 16:38
483 查看
简单的递归回溯法,锻炼基本的编程能力。
这类题是对代码能力的要求比对思想的要求高点。
而且要审题,题目要求安lexicographically 顺序输出,不小心递归的顺序就会输出错误了。
棋盘是由数字列或者行,和字母列或者行组成的,故此输出结果要注意。
个人觉得我的递归回溯写法是非常清晰, 工整的,O(∩_∩)O哈哈~
这类题是对代码能力的要求比对思想的要求高点。
而且要审题,题目要求安lexicographically 顺序输出,不小心递归的顺序就会输出错误了。
棋盘是由数字列或者行,和字母列或者行组成的,故此输出结果要注意。
个人觉得我的递归回溯写法是非常清晰, 工整的,O(∩_∩)O哈哈~
#include <stdio.h> #include <string.h> const int MAX_N = 27; bool board[MAX_N][MAX_N]; int res[MAX_N*MAX_N]; int row, col, total, id; inline bool isLegal(int r, int c) { return 0<=r && 0<=c && r<row && c<col && !board[r][c]; } bool getTourPath(int r = 0, int c = 0, int n = 0)//r为字母, c为数字 { if (n == total) return true; if (!isLegal(r, c)) return false; res[id] = r, res[id+1] = c;//record result board[r][c] = true;//mark ++++id, ++n; if (getTourPath(r-2, c-1, n)) return true; if (getTourPath(r-2, c+1, n)) return true; if (getTourPath(r-1, c-2, n)) return true; if (getTourPath(r-1, c+2, n)) return true; if (getTourPath(r+1, c-2, n)) return true; if (getTourPath(r+1, c+2, n)) return true; if (getTourPath(r+2, c-1, n)) return true; if (getTourPath(r+2, c+1, n)) return true; ----id, --n; board[r][c] = false;//unmark return false; } int main() { int T; scanf("%d", &T); for (int t = 1; t <= T; t++) { printf("Scenario #%d:\n", t); scanf("%d %d", &col, &row); memset(board, 0, sizeof(board)); total = col*row; id = 0; if (getTourPath()) { for (int i = 0; i < id; i += 2) { putchar(char(res[i]+'A')); putchar(char(res[i+1]+'1')); } putchar('\n'); } else puts("impossible"); putchar('\n'); } return 0; }
相关文章推荐
- POJ训练计划2488_A Knight's Journey(DFS+回溯)
- poj 2533 N皇后问题 -- 递归回溯(打表)
- POJ 2488 A Knight's Journey【DFS + 回溯应用】
- POJ 1011 递归 &amp; 回溯
- poj2488 回溯 注意字典 边缘的处理思想
- POJ 2488 A Knight's Journey【DFS + 回溯应用】
- 数据结构(四)递归与回溯——POJ-1011 dfs+剪枝
- POJ 2488 A Knight's Journey DFS 深搜回溯
- poj 2488 深搜+回溯
- poj_1166_枚举(或者递归/回溯)
- 【poj 2488】A Knight's Journey 中文题意&题解&代码(C++)
- ★Uva 1626 && POJ 1141 Brackets sequence 详细题解(区间DP+递归打印)
- poj The Settlers of Catan( 求图中的最长路 小数据量 暴力dfs搜索(递归回溯))
- 经典回溯——POJ 2488
- POJ-2488 国际象棋马的走法 (深度优先搜索和回溯)
- POJ 2488 回溯
- POJ 2488 A Knight's Journey(DFS+回溯)
- poj 2488 dfs+回溯
- POJ 2488 DFS+回溯
- POJ-2488(回溯+剪枝)