資料結構迷宮問題C 實現

2021-08-01 18:17:24 字數 2463 閱讀 8978

出現實現圖:

.h檔案實現堆疊簡易操作(此處沒有將宣告與實現分離,應注意!)

#pragma warning (disable : 4715)

#ifndef stack_h

#define stack_h

struct position//結構體位置,表示迷宮每一格的行號和 列號

;class stack

; bool isempty() const

bool isfull() const

position top() const;//返回棧頂元素

stack& add(position &x);//新增元素

stack& delete(position &x);//刪除元素

private:

int top;//棧頂,入棧和出棧的地方。

int maxtop;//棧頂元素位置。

position *element;

};stack::stack(int maxsize)

position stack::top() const

else

return element[top];

}stack& stack::add(position &x)

else

return *this;

}stack& stack::delete(position &x)

else

return *this;

}#endif

原始檔:

#include#include"stack.h"

using namespace std;

int main()

//構建迷宮,用符號+表示牆壁,空格表示通路,以使迷宮盡可能好看!

for (int a = 1; a < 11; ++a)

for (int b = 1; b < 11; ++b)

maze[a][b] = ' ';

for (int i = 2; i < 7; ++i)

maze[1][i] = '+';

maze[2][6] = maze[2][8] = maze[3][4] = maze[3][6] = maze[4][2] = maze[4][4] = maze[4][6] = maze[4][8] = maze[4][9] = '+';

maze[5][2] = maze[5][4] = maze[5][6] = maze[5][8] = maze[6][2] = maze[6][3] = maze[6][4] = maze[6][6] = maze[6][8] = maze[6][10] = '+';

maze[7][2] = maze[7][6] = maze[7][8] = maze[7][10] = maze[8][2] = maze[8][4] = maze[8][5] = maze[8][6] = maze[8][8] = '+';

maze[9][1] = maze[9][8] = maze[10][5] = maze[10][6] = maze[10][7] = maze[10][8] = '+';

//輸出迷宮 布局。

cout << "迷宮如下所示:" << endl;

for (int a = 0; a < 12; ++a)

//構建迷宮完畢,開始尋找路徑。

stack* path = new stack(10*10 - 1);//棧用來儲存路徑以及遇到障礙物時方標返回上一步。

position offset[4];//設定模擬移動方法。

offset[0].row = 0; offset[0].col = 1;//右移

offset[1].row = 1; offset[1].col = 0;//下移

offset[2].row = 0; offset[2].col = -1;//左移

offset[3].row = -1; offset[3].col = 0;//上移

position here;//代表當前位置。

here.col = 1;

here.row = 1;

maze[1][1] = '#';//入口堵住,防止返回入口。

int option = 0;//上、下、左、右四種走法。記錄走的次數,一共四次,上下左右分布探索。

int lastoption = 3;

//模擬移動,開始尋找出口。

while (here.row != 10 || here.col != 10)

if (option <= lastoption)

else//不是通路,會退一步,路徑記錄棧棧頂元素出棧。

}cout << "老鼠找到了迷宮的出口!!" << endl;//以圖形的樣式輸出尋找得到的路徑。

for (int i = 0; i < 12; ++i)

system("pause");

}

c資料結構 棧 迷宮問題(迴圈實現)

走迷宮步驟 使用二維陣列來表示迷宮地圖。1表示可以走,0表示不能走。設定迷宮入口。判斷迷宮入口是否合法。將入口點入棧 將當前點設定為入口點。loop 判斷是否能往左走,能則將當前點壓棧。goto loop 判斷是否能忘上走,能則將當前點壓棧。goto loop 判斷是否能往右走,能則將當前點壓棧。g...

資料結構 迷宮問題

迷宮問題的總體思路是,從迷宮的入口出發,沿著某乙個方向向前試探,若能夠行得通,則繼續往前走,否則原來返回,再換另乙個方向繼續試探,直到所有可能的通路都被試探過,為了保證在任何乙個位置都能夠原來返回,需要設定乙個堆疊結構來儲存從入口到當前位置的路徑。maze.h pragma once include...

資料結構 迷宮問題

設計乙個迷宮求解程式,要求如下 以m n表示長方陣表示迷宮,求出一條從入口到出口的通路,或得出沒有通路的結論。能任意設定的迷宮 include using namespace std define maxsize 1000 int mg maxsize maxsize typedef structb...