您的位置:首页 > 编程语言 > C语言/C++

迷宫的递归算法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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: