迷宫的递归算法c++

可以找到所有的路径

 

 

#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; }

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/leonard520/article/details/5747625
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞