用棧實現迷宮問題求解

來源:互聯網
上載者:User

來源程式:
 
//base.h
#include 
#include 
#include 
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
 
//stack.h
#include "base.h"
#define INIT_SIZE 100 //儲存空間初始分配量
#define INCREMENT 10  //儲存空間分配增量
typedef struct{       //迷宮中r行c列的位置
         int r;
         int c;
}PostType;
typedef struct{
         int ord;      //當前位置在路徑上的序號
         PostType seat;//當前座標
         int di;       //往下一座標的方向
}SElemType;        //棧元素類型
typedef struct{
         SElemType* base;//棧基址,構造前銷毀後為空白
         SElemType* top;//棧頂
         int stackSize;  //棧容量
}Stack;             //棧類型
Status InitStack(Stack &S){  //構造空棧s
         S.base=(SElemType*)malloc(INIT_SIZE *sizeof(SElemType));
         if(!S.base)
                   exit(OVERFLOW);//儲存分配失敗
         S.top=S.base;
         S.stackSize=INIT_SIZE;
         return OK;
}//InitStack
Status StackEmpty(Stack S){         
//若s為空白返回TRUE,否則返回FALSE
         if(S.top==S.base)
                   return TRUE;
         return FALSE;
}//StackEmpty
Status Push(Stack &S,SElemType e){
 //插入元素e為新的棧頂元素
         if(S.top-S.base >=S.stackSize){//棧滿,加空間
                   S.base=(SElemType *)realloc(S.base,(S.stackSize+INCREMENT)*sizeof(SElemType));
                   if(!S.base)
                            exit(OVERFLOW);   //儲存分配失敗
                   S.top=S.base+S.stackSize;
                   S.stackSize+=INCREMENT;
         }
         *S.top++=e;
         return OK;
}//push
Status Pop(Stack &S,SElemType &e){//若棧不空刪除棧//頂元素用e返回並返回OK,否則返回ERROR
         if(S.top==S.base)
                   return ERROR;
         e=*--S.top;
         return OK;
}//Pop
Status DestroyStack(Stack &S){//銷毀棧S,
         free(S.base);
         S.top=S.base;
         return OK;
}//DestroyStack

</

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.