迷宫搜索(链表栈)

以前写搜索都是果断STL......

深搜和广搜借助到STL 的stack 和queue。。。

今天写了一下链表栈(这么叫怪怪的)的搜索,挺好写的。。

下面给出代码吧

#include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;
bool vis[1000][10000];
int map[5][5]={
    {0,0,0,0,0},
    {0,1,0,1,0},
    {0,1,1,0,0},
    {0,1,1,0,1},
    {0,0,0,0,0}
};
int m,n;
int point[4][2]={1,0,0,1,-1,0,0,-1};
int startx,starty,endx,endy;
int e1,e2;
int ans=1;
typedef struct linknode
{
    int xx,yy;
    struct linknode *next;
}LinkStNode;
void InitStack(LinkStNode *&s)
{
    s=(LinkStNode *)malloc(sizeof(LinkStNode));
    s->next=NULL;
}
void DestoryStack(LinkStNode *&s)
{
    LinkStNode *pre=s,*p=s->next;
    while(p!=NULL)
    {
        free(pre);
        pre=p;
        p=p->next;
    }
    free(pre);
}
bool StackEmpty(LinkStNode *s)
{
    return s->next==NULL?true:false;
}
void push(LinkStNode *&s,int e1,int e2)
{
    LinkStNode *p;
    p=(LinkStNode *)malloc(sizeof(LinkStNode));
    p->xx=e1;
    p->yy=e2;
    p->next=s->next;
    s->next=p;
}
bool pop(LinkStNode *&s)
{
    LinkStNode *p;
    if(s->next==NULL)
        return false;
    p=s->next;
    s->next=p->next;
    free(p);
    return true;
}
LinkStNode GetTop(LinkStNode *s)
{
    linknode xy;
    if(s->next==NULL){
        xy.xx=-1;
        xy.yy=-1;
    }
    else{
        xy.xx=s->next->xx;
        xy.yy=s->next->yy;
    }
    return xy;
}
bool check(int x,int y){
    if(map[x][y]==0&&vis[x][y]==false)
        return true;
    return false;
}
void display(LinkStNode *&s){
    linknode xy;
    if(!StackEmpty(s)){
        xy=GetTop(s);
        pop(s);
        display(s);
    }
    if(StackEmpty(s)){
        push(s, -1, -1);
          return;
    }
    if(xy.xx!=-1&&xy.yy!=-1)
    {
         cout<<"("<<xy.xx<<","<<xy.yy<<")";
        push(s, xy.xx, xy.yy);
    }
    
    
}
void display1(LinkStNode *&s){
    while(!StackEmpty(s)){
        linknode p=GetTop(s);
        if(p.xx!=-1&&p.yy!=-1)
        cout<<p.xx<<"  "<<p.yy<<endl;
        pop(s);
    }
}
void DFS(LinkStNode *&s ,int x,int y){
    vis[x][y]=true;
    push(s,x,y);
    if(x==endx&&y==endy){
        cout<<endl<<"路径"<<ans++<<endl;
        display(s);
        cout<<endl;
    }
    for(int i=0;i<4;i++){
        int x1=x+point[i][0];
        int y1=y+point[i][1];
        if(x1>=0&&x1<m&&y1>=0&&y1<n&&check(x1, y1)){
            DFS(s,x1,y1);
            vis[x1][y1]=false;
            pop(s);
        }
    }
}
int main()
{
    LinkStNode *s;
    InitStack(s);
    cout<<"输入大小"<<endl;
    //cin>>m>>n;
    m=5;n=5;
    cout<<"输入地图"<<endl;
    //for(int i=0;i<m;i++)
    //    for(int j=0;j<n;j++)
    //        cin>>map[i][j];
    cout<<"输入起点"<<endl;
    //cin>>startx>>starty;
    startx=0;starty=0;
    cout<<"输入终点"<<endl;
    //cin>>endx>>endy;
    endx=4;
    endy=4;
    memset(vis ,false,sizeof vis);
    DFS(s,startx,starty);
}

猜你喜欢

转载自blog.csdn.net/qq_41421433/article/details/82945181