一个递归问题
2014-05-11 19:03
190 查看
// Created by baicai on 14-5-10. // 递归问题 /* 递归中两个重要的点 : 1.递归公式 2.终止条件 */ /* 函数的局部变量存在栈中,可能会栈溢出,所以可以考虑使用全局数组,或者动态分配数组 */ /* 游戏问题: 类似迷宫求解,自相似性表现在每走一步的探测方式相同,可以用递归方法求解, 通过枚举出所有从起点到终点的路径 */ // 需要一个记录 // 方向数组 to[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; /* for(int i=0;i<4;i++) int x = now_x + to[i][0]; int y = now_y + to[i][1]; f = i; // 方向 限制: 边界 (x > -1) && x<( w+2) && (y>-1) && (y< h+2) 有没有游戏卡片曾走过 ((board[y][x] == ' ') && ( mark[y][x] == false )) 已经到达终点 (x == end_x) && (y == end_y) && (borad[y][x] == 'X') 终止条件: T1&&(T2||T3) */ #include <stdio.h> #include <memory.h> #include <iostream> using namespace std; int W; int H; int board[77][77]; int to[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; // 东南西北 bool mark[77][77]; // 标记是否走过 int minstep; int count; void Search(int x,int y,int x_end,int y_end,int f,int step){ /* 终止条件 */ if (step > minstep) { return; } if (x == x_end && y == y_end) { if (step < minstep) { minstep = step; return; } } // 枚举搜寻方向 for (int i = 0; i < 4; i++) { int _x = x + to[i][0]; int _y = y + to[i][1]; // 在下列几种情况下 继续递归 在板内的情况的 1. 找到 2. 没有走过 3. if ((((_x > -1) && _x < (W+2) && (_y>-1)&&(_y<H+2)) && (((_x == x_end)&&(_y == y_end) && board[_y][_x]=='X' ) || (((mark[_y][_x] ==false && (board[_y][_x] == ' '))))))) { mark[_y][_x] = true; if (f == i) { Search(_x, _y, x_end, y_end, i, step); } else{ Search(_x, _y, x_end, y_end, i, step+1); } mark[_y][_x] = false; } } } int main(){ int Boardnum = 0; while (cin>>W>>H) { if (W==0 && H == 0) { break; } ++Boardnum; printf("Board #%d:\n",Boardnum); int i,j; for (i = 0; i < (W+2); i++) { board[0][i] = board[i][0] = ' '; } for (i = 1 ; i<=H; i++) { getchar(); // 丢弃回车 for (j=1; j<=W; j++) { board[i][j] = getchar(); } } for (i=0; i<=W; i++) { board[H+1][i+1] = ' '; board[i+1][W+1] = ' '; } int begin_x,begin_y,end_x,end_y,count = 0; while (cin>>begin_x>>begin_y>>end_x>>end_y) // 少了一些条件语句 { count++; memset(mark, false, sizeof(mark)); minstep = 9999999; Search(begin_x, begin_x, end_x, end_y, -1, 0); if (minstep < 9999999) { cout<<"Pari"<<count<<" "<<"segment:"<<minstep<<endl; } else cout<<"impossibe"<<count<<endl; } cout<<endl; } return 0; }
相关文章推荐
- 迷宫问题用递归求全部解和用栈求一个解(C++)
- 这是一个字符的全排列问题,里面的递归不是太懂
- printdigit打印小数的一个问题,递归(问题)
- JavaScript使用递归遇到的一个问题
- 剑指offer——面试题39:扩展问题判断一个树是否是平衡二叉树(递归)
- 怎么判断一个问题是不是递归的
- 八皇后非递归(仅使用一个数组且可扩展为N皇后问题)
- 折半查找实现算法二(递归办法)PS:编译后有一个warning,但不影响结果,代码设计上应该还有些问题
- 递归解决输出一个字符串的全排列问题(缺陷:没有考虑字符串中字符重复的问题)
- java 递归的一个问题记录
- 一个简单的递归问题
- C++递归问题之二——n皇后问题:以四、八皇后为例,给定n个皇后要求将它们放在一个n维矩阵中,任意两个皇后不能出现在同一行、列、主副对角线上,输出具体的摆放方式
- 一天一个算法题-简单的-递归-猴子吃桃问题
- python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
- 递归问题之一:给定一字符串,输出字符串中所有字符子串的各种组合形式,长度为一个字符到字符串的长度,忽略排序
- 一个循环递归遍历问题
- 用递归法:设计算法求解汉诺塔问题,并编程实现。 (1) Hanoi(汉诺)塔问题分析 这是一个古典的数学问题,是一个用递归方法解题的典型例子。问题是这样的:古代有一个梵塔,塔内有3个座 A,B,C
- 递归一个值得思考的问题
- 求助:递归地读取一个路径下文件总行数遇到的问题。
- swift override --有一个递归问题未解决