這篇部落格是借鑑了always__的部落格修改得到了,感謝他的幫助。
採用了以棧為基礎,在棧的基礎上進行迷宮的求解,用stack和maze兩個檔案來實現功能。
stack.h的實現如下:
stack.cpp實現如下:#pragma once
#include #include #include #include typedef int directivetype; //下乙個通道方向
#define range 100 //迷宮大小
#define stack_init_size 100
#define stackincrement 10
//------------ 棧的順序儲存實現 ------------------------------
typedef struct
postype; //座標(row,col)
typedef struct
selemtype; //棧的元素型別
typedef struct
sqstack;
bool initstack(sqstack &s); //棧的建立,即構造乙個空棧
bool gettop(sqstack s,selemtype &e); //如棧不為空,用e返回棧頂元素
bool push(sqstack &s, selemtype e); //在棧中插入元素
bool pop(sqstack &s, selemtype &e); //刪除棧頂元素
bool stackempty(sqstack s); //判斷棧為不為空
bool destorystack(sqstack &s); //銷毀棧
maze.h實現如下:#include "stack.h"
#include "maze.h"
bool initstack(sqstack &s)
s.top=s.base;
s.stacksize=stack_init_size;
return true;
}bool gettop(sqstack s, selemtype &e )
e = *(s.top-1);
return true;
}bool push(sqstack &s, selemtype e)
s.top = s.base + s.stacksize;
s.stacksize += stackincrement;
}*s.top++ = e;
return true;
}bool pop(sqstack &s, selemtype &e)
bool stackempty(sqstack s)
bool destorystack(sqstack &s)
maze.cpp實現如下:typedef int directivetype; //下乙個通道方向
#define range 100 //迷宮大小
#define row 10 //迷宮的行數
#define col 10 //迷宮的列數
typedef struct
mazetype;
bool initmaze(mazetype &maze, int a[row][col], int row, int col);//初始化迷宮
bool pass(mazetype maze,postype curpos); //判斷能否通過
bool footprint(mazetype &maze,postype curpos); //留下足跡
bool markprint(mazetype &maze,postype curpos); //留下不能通過的標記
postype nextpos(postype curpos, directivetype di); //curpos當前位置
//返回當前節點的下一節點
bool posequal(postype pos1, postype pos2); //判斷兩節點是否相等
void printmaze(mazetype maze,int row,int col);
bool mazepath(mazetype &maze,postype start, postype end); //求解一條路徑
測試截圖如下:#include "stack.h"
#include "maze.h"
bool initmaze(mazetype &maze, int a[row][col], int row, int col)
, ,
, ,
, ,
, ,
, }; printf("\n----------原始迷宮(加外圍圍牆)(0 表示通路,1 表示障礙)---------\n");
for(i=0;i<10;i++)
printf("\n");
} initmaze(maze,a,row,col);
do else
}while(flag);
doelse
}while(flag);
if(mazepath(maze,start,end))//找到一條路徑
else
printf("\n 需要繼續嗎?: ");
scanf(" %c",&cmd);
}while(cmd=='y'||cmd=='y');
}
有什麼問題請大家指出,謝謝。
棧 求解迷宮
檔名稱 main.cpp 完成日期 2016 年 7 月 1 日 版本號 v1.0 問題描述 編寫乙個求解迷宮問題 include include define maxsize 100 define n 4 列號 define m 4 行號 int mg m 2 n 2 struct stack m...
棧求解迷宮問題
問題 假設下圖1是某迷宮的地圖 0代表路徑,1代表牆壁 問此迷宮是否有條通路?求解思想 用棧來實現解決問題,主要步驟是 1 將迷宮的入口座標設為當前座標 2 將當前座標壓棧,將當前座標上的值設為2 0變為2 代表已走過的路 3 判斷當前座標的四周 上下左右 是否是可以通 為0則通 的,如果是通的,那...
棧 求解迷宮問題
問題 在迷宮中尋找一條路徑 演算法分析 將迷宮數值化,使用二維陣列來表示迷宮,牆單元用0,通道單元用1 如果能夠通過繼續前進,如果不能通過則退回到上乙個單元,因此用棧來儲存通過的路徑 用0,1,2,3來分別表示4個方向 include pch.h include include include in...