迷宮問題求解——數據結構C語言的棧算法實現

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Status int

char a[10][10]={
{‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’},
{‘0’,‘1’,‘1’,‘0’,‘1’,‘1’,‘1’,‘0’,‘1’,‘0’},
{‘0’,‘1’,‘1’,‘0’,‘1’,‘1’,‘1’,‘0’,‘1’,‘0’},
{‘0’,‘1’,‘1’,‘1’,‘1’,‘0’,‘0’,‘1’,‘1’,‘0’},
{‘0’,‘1’,‘0’,‘0’,‘0’,‘1’,‘1’,‘1’,‘1’,‘0’},
{‘0’,‘1’,‘1’,‘1’,‘0’,‘1’,‘1’,‘1’,‘1’,‘0’},
{‘0’,‘1’,‘0’,‘1’,‘1’,‘1’,‘0’,‘1’,‘1’,‘0’},
{‘0’,‘1’,‘0’,‘0’,‘0’,‘1’,‘0’,‘0’,‘1’,‘0’},
{‘0’,‘0’,‘1’,‘1’,‘1’,‘1’,‘1’,‘1’,‘1’,‘0’},
{‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’,‘0’}
};

//位置類型
typedef struct
{
int row;//行
int col;//列
}PosType;

//棧元素類型
typedef struct
{
int ord;//通道塊在該路徑上的序號
PosType seat;//通道塊在迷宮中的座標位置
int di;//從此通道塊走向下一通道塊的方向
}SElemType;

//指向棧元素類型的指針
typedef struct LNode
{
SElemType data;
LNode *next;
}LNode,*LinkStack;

//構造空棧
Status InitStack(LinkStack &S)
{
if(!S)
{
S = (LinkStack)malloc(sizeof(SElemType));
S->next = NULL;
return 1;
}
else
return 0;
}

//若棧不空,刪除元素,用e返回其值
Status Pop(LinkStack &S,SElemType &e)
{
LNode *p=S,*q;
if(!p->next)//棧爲空
{
return 0;
}
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return 1;

}

//插入新的棧頂元素
Status Push(LinkStack &S,SElemType e)
{
LNode *p=S,*q;
if(!p)
return 0;
q = (LinkStack)malloc(sizeof(LNode));//定義s的類型,新建一個節點
q->data = e;
q->next = p->next;
p->next = q;
return 1;
}

//判斷當前位置是否可以通過
Status Pass(PosType e)
{
if(a[e.row][e.col]==‘1’)
return 1;
else
return 0;
}

//記錄可以通過的路徑,避免走回頭路
void Footprint(PosType e)
{
a[e.row][e.col] = ‘X’;
}

//繼續走下一步
PosType Nextpos(PosType curpos,int x)
{
if(x1)
curpos.col=curpos.col+1;//規定向東
else if(x
2)
curpos.row= curpos.row+1;//規定向南
else if(x==3)
curpos.col= curpos.col-1;//規定向西
else
curpos.row= curpos.row-1;//規定向北
return curpos;
}

//不能通過的留下標記
void Markprint(PosType e)
{
a[e.row][e.col] = ‘@’;
}

//判斷棧是否爲空
Status StackEmpty(LinkStack &S)
{
if(S->next==NULL)
return 1;
else
return 0;
}

//開始迷宮找路徑
void MazePath(PosType start,PosType end)
{
LinkStack S = NULL;
InitStack(S);
SElemType e;
PosType curpos;//定義當前位置
int curstep=1;//記錄路徑序號
curpos = start;
do{
if(Pass(curpos))//當前位置可以通過
{
Footprint(curpos);//留下足跡
e.ord = curstep;//記錄該位置路徑序號
e.seat = curpos;//記錄該位置座標
e.di = 1;//以東爲初始方向
Push(S,e);
if(curpos.row == end.row && curpos.col == end.col)
break;
curpos = Nextpos(curpos,1);//下一個位置是當前位置的東鄰,
curstep++;//探索下一步,記錄路徑序號
}
else//當前位置不能通過
{
if(!StackEmpty(S))
{
Pop(S,e);//將上一if語句放入棧頂的元素提取出來,判斷其方向是否已全部走完
while(e.di==4 && !StackEmpty(S))
{
Markprint(e.seat);//留下不能通過的標記
Pop(S,e);//退回一步,提取新的棧頂元素判斷是否還存在其他方向,直到找到新的路徑爲止
}
if(e.di<4)
{
e.di++;
Push(S,e);
curpos = Nextpos(e.seat,e.di);
}
}
}
}while(!StackEmpty(S));
}

void main()
{
int i,j;
PosType start,end;//定義入口位置和出口位置
start.row = 1;
start.col = 1;
end.row = 8;
end.col = 8;
printf(“創建迷宮!\n”);
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
printf("%4c",a[i][j]);
printf("\n");
}
MazePath(start,end);
printf(“出口路線爲:\n”);
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
printf("%4c",a[i][j]);
printf("\n");
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章