資料結構 迷宮 代碼

來源:互聯網
上載者:User

 #include<stdio.h>

#include<iostream>#include<stdlib.h>#include<time.h>#define STACK_INIT_SIZE 1000#define STACKINCREMENT 10#define OK 1#define OVERFLOW 0#define ERROR 0 //typedef int SElemType;typedef struct SElemType{int x;int y;};typedef struct{SElemType *base;SElemType *top;int stacksize;}SqStack;int InitStack(SqStack &S){S.base=(SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));if(!S.base) exit(OVERFLOW);S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}void Push(SqStack &S,SElemType &e){if(S.top-S.base>=S.stacksize){S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));if(!S.base) exit (OVERFLOW);S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;}SElemType Pop(SqStack &S,SElemType &e){//if(S.top==S.base) return ERROR;e=*--S.top;return e;}SElemType GetTop(SqStack S,SElemType &e){e=*(S.top-1);return e;} int StackEmpty(SqStack &S) {//若棧S為空白棧,則返回OK,否則返回ERRORif(S.base==S.top)return OK;elsereturn ERROR;}  int main(){int m;SqStack S;InitStack(S);printf("請輸入迷宮的大小(m*m)");scanf("%d",&m);//數組的形式表示八個方向int move[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1, 0},{-1, 1}};//用結構體表示位置struct position{int x,y;};//用於記錄和輸出迷宮探路中相關符號,包括1 .char maze[20][20];//用棧來儲存探路過程中的資料int i,x,y,ok;    SElemType p;//二維數組的第0行、第m+1行、第0列、第m+1列元素全//置成“1”,表示迷宮的邊界;第1行第1列元素和第m行第m列//元素置成“0”,表示迷宮的入口和出口;其餘元素值用隨機//函數產生。srand(time(0));for(x=1;x<=m;x++)for(y=1;y<=m;y++)maze[x][y]=48+rand()%2;maze[1][1]='0';maze[m][m]='0';for(x=0;x<=m+1;x++){maze[x][0]='1';maze[x][m+1]='1';}for(y=0;y<=m+1;y++){maze[0][y]='1';maze[m+1][y]='1';}p.x=1;p.y=1;Push(S,p);maze[1][1]='.';printf("迷宮初始為(m*m)/n");for(x=1;x<=m;x++){printf("/n");for(y=1;y<=m;y++) printf("%c ",maze[x][y]);}printf("/n");//開始探路do{GetTop(S,p);ok=0;i=0;while((ok==0)&&(i<8)){x=p.x+move[i][0];y=p.y+move[i][1];if(maze[x][y]=='0'){p.x=x;p.y=y;Push(S,p);maze[x][y]='.';ok=1;}i++;}if(i==8){maze[p.x][p.y]='*';Pop(S,p);}}while((!StackEmpty(S))&&((p.x!=m)||(p.y!=m)));//輸出探路結果if(StackEmpty(S)) printf("沒有路徑/n");else printf("有路徑/n");//輸出探路迷宮留下的蹤跡for(x=1;x<=m;x++){printf("/n");for(y=1;y<=m;y++) printf("%c ",maze[x][y]);}printf("/n");    system("pause"); }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.