迷宫的递归算法c++
2010-07-19 21:53
288 查看
可以找到所有的路径
#include <iostream> #include <stack> using namespace std; struct Node { int x; int y; bool visit; int value; }matrix[ 2 ][ 2 ]; int sum = 0; int nearest = 100; stack< Node > s; void print( stack< Node > s, int endx, int endy ) { sum ++; cout << "ans " << sum << " :"; stack< Node > t; while( !s.empty() ) { t.push( s.top() ); s.pop(); } while( !t.empty() ) { Node n = t.top(); cout << "( " << n.x << ", " << n.y << " ) -> "; s.push( n ); t.pop(); } cout << "( " << endx << ", " << endy << " )"; cout << endl; } bool isVaild( int x ) { return ( x >= 0 && 2 > x ); } void search( int startx, int starty, int endx, int endy ) { s.push( matrix[ startx ][ starty ] ); int tempx, tempy; Node n = s.top(); tempx = n.x; tempy = n.y; if( isVaild( tempx - 1 ) && isVaild( tempy ) && ( matrix[ tempx - 1 ][ tempy ].visit == false ) && ( matrix[ tempx - 1 ][ tempy ].value == 0 ) ) { if( ( tempx - 1 == endx ) && ( tempy == endy ) ) print( s, endx, endy ); else { matrix[ tempx - 1 ][ tempy ].visit = true; search( n.x - 1, n.y, endx, endy ); } } if( isVaild( tempx ) && isVaild( tempy - 1 ) && ( matrix[ tempx ][ tempy - 1 ].visit == false ) && ( matrix[ tempx ][ tempy - 1 ].value == 0 ) ) { if( ( tempx == endx ) && ( tempy - 1 == endy ) ) print( s, endx, endy ); else { matrix[ tempx ][ tempy - 1 ].visit = true; search( n.x , n.y - 1, endx, endy ); } } if( isVaild( tempx ) && isVaild( tempy + 1 ) && ( matrix[ tempx ][ tempy + 1 ].visit == false ) && ( matrix[ tempx ][ tempy + 1 ].value == 0 ) ) { if( ( tempx == endx ) && ( tempy + 1 == endy ) ) print( s, endx, endy ); else { matrix[ tempx ][ tempy + 1 ].visit = true; search( n.x, n.y + 1, endx, endy ); } } if( isVaild( tempx + 1 ) && isVaild( tempy ) && ( matrix[ tempx + 1 ][ tempy ].visit == false ) && ( matrix[ tempx + 1 ][ tempy ].value == 0 ) ) { if( ( tempx + 1 == endx ) && ( tempy == endy ) ) print( s, endx, endy ); else { matrix[ tempx + 1 ][ tempy ].visit = true; search( n.x + 1, n.y, endx, endy ); } } s.pop(); } int main() { int i, j; for( i = 0; i < 2; i++ ) for( j = 0; j < 2; j++ ) { matrix[ i ][ j ].x = i; matrix[ i ][ j ].y = j; matrix[ i ][ j ].value = false; cout << "input ( " << i << ", " << j << " ): "; cin >> matrix[ i ][ j ].value; } matrix[ 0 ][ 0 ].visit = true; search( 0, 0, 1, 1 ); if( sum == 0 ) cout << " no route " << endl; return 0; }
相关文章推荐
- ai2790-迷宫-C语言-递归算法
- C++迷宫
- c++迷宫代码
- 迷宫问题,c/c++ 各显身手
- 迷宫求解C++
- C++ 找出迷宫的最短路径
- 使用C++编写简单的迷宫游戏
- 数据结构迷宫问题C++实现
- C++ 编写的栈解迷宫程序
- 4000 C++ 递归算法
- 2013 C++第一周任务 递归算法
- 迷宫问题求解(C++非递归程序)
- C++实现迷宫问题
- 逃出迷宫完整算法C++
- C++:单链表逆置的递归算法和非递归算法
- C++实现递归算法
- [C++]数据结构课程设计:迷宫老鼠1.0
- 迷宫问题递归算法
- C++初学之 2.递归算法典型案例: 斐波那契(Fibonacci)兔子问题(第三项为前两项的累加问题)
- 数据结构与算法之递归算法 C++和PHP实现