/************************************
名 称:迷宫问题
作 者:freewind
版 本:v1.0
时 间:2006-08
Email:freewind22@163.com
*************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define Type int
typedef struct
{
Type * top;
Type * base;
int size;
}Stack;
void InitStack( Stack * sk )
{
sk->top=(Type *)malloc( STACK_INIT_SIZE * sizeof(Type) );
sk->base=sk->top;
sk->size=STACK_INIT_SIZE;
}
void DestroyStack( Stack * sk )
{
free( sk->base );
}
Type Pop( Stack *sk )
{
if( sk->top !=sk->base )
return *--sk->top;
return 0;
}
void Push( Stack *sk, Type d )
{
if( sk->top - sk->base > sk->size )
{
printf("堆栈已满/n");
exit(0);
}
*sk->top++=d;
}
int IsEmpty( Stack *sk )
{
if ( sk->top == sk->base )
return 1;
else
return 0;
}
void ShowMap( int map[12][12],int n)
{ /*★☆☆★○●◎◇◆□■△▲※*/
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(map[i][j]==1) printf("■");
else if(map[i][j]>=2) printf("→");
else if(map[i][j]==-10) printf("★");
/*else if(map[i][j]<0 ) printf("%d",map[i][j]);*/
else printf(" ");
}
printf("/n");
}
}
void FindPath( int map[12][12], int startx,int starty, int end, int wall, int lu)
{
int i,j,Found=0;
int nextx,nexty;
Stack sk;
InitStack( &sk );
Push( &sk, startx );
Push( &sk, starty );
i=startx,j=starty;
while( !Found )
{
nextx=i,nexty=j;
switch( map[i][j] )
{
case 0: nextx++; break;
case -1: nexty++; break;
case -2: nextx--; break;
case -3: nexty--; break;
case -4:
j=Pop( &sk );
i=Pop( &sk );
if( map[i][j] !=-4 )
{
Push( &sk,i );
Push( &sk,j );
}
if ( !i ) {
printf("无解!");exit(0);
}
continue;
}/* end switch */
map[i][j]--;
if( map[nextx][nexty]==end ){
Found=1;break; }
if( map[nextx][nexty]==lu )
{
Push( &sk, nextx);
Push( &sk, nexty);
i=nextx,j=nexty;
continue;
}
}
if( Found )
{
while( j=Pop( &sk ))
{
i=Pop( &sk );
map[i][j]=-10;
}
}
DestroyStack( &sk );
}
void main()
{
int map[12][12]={
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1},
{ 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1},
{ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{ 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1},
{ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1},
{ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1},
{ 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1},
{ 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1},
{ 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 3, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
ShowMap( map, 12);
FindPath(map,1,1,3,1,0);
ShowMap( map, 12);
}