迷宮問題 c語言棧實現

2021-08-24 17:48:08 字數 2331 閱讀 8431

我們用乙個二維陣列表示迷宮的點,1能走,0不能走,用回溯法寫,用乙個簡單一點的迷宮做事例:

#define _crt_secure_no_warnings 1

#include #include #include #define n 6 //n*n的迷宮

#define length n * n//最大行走步數

typedef struct pos

pos;

typedef struct stack

stack;

void pathprint();//列印路徑

void mazegetshortpath(pos entry, stack* path);//從第一部開始走

void mystackinit(stack* s);//棧初始化

void zoulu(pos now, int* arr);//走每一步的判斷以及遞迴

void mystackpush(stack* s, pos x);//壓入棧

pos mystackpop(stack* s);//彈出棧

int stackempty(stack* s);//判空棧

stack path;//定義路徑棧

stack* s = &path;//定義路徑棧的指標,指向這個存放路徑棧

pos enterpoint;//起點

pos finalpoint;//終點

int count = 0;//統計一共多少種走法

//------------------分割線,以上皆為標頭檔案-----------------------------

void pathprint()

s->_end = tmp;//_end指標回到棧底

}void zoulu(pos now, int arr[n][n])

//沒到終點的情況:

if (1 == arr[now.x - 1][now.y] && now.x - 1 >= 0)//如果now點的上面可以走並且不超過棋盤

if (1 == arr[now.x + 1][now.y] && now.x + 1 < n)//下面的點可走

if (1 == arr[now.x][now.y - 1] && now.y - 1 >= 0)//左邊點

if (1 == arr[now.x][now.y + 1] && now.y + 1 < n)//右邊點

//如果都不可以走,說明是當前走的這條路的死路,就彈出這個點,並且重置。

//當前遞迴層次結束會返回到上次呼叫的地方,並不會走重複路,這是**核心。

pos p = mystackpop(s);

arr[p.x][p.y] = 1;

}void mazegetshortpath(pos entry, stack* path, int arr[n][n])

void mystackinit(stack* s)

//初始化棧陣列空間

s->_top = s->_end;//最開始棧頂等於棧低

s->stacksize = length;

return;

}void mystackpush(stack* s, pos x)

s->_top = s->_end + s->stacksize;//設定棧頂

s->stacksize += length;//設定棧長度

} *(s->_top) = x;//設定x

s->_top++;//指標後移

return;

}int stackempty(stack* s)

pos mystackpop(stack* s)

return *--(s->_top);//棧頂指標下移並取出那個值

}int main()

, ,

, ,

, ,

}; //設定起點和終點座標

enterpoint.x = 5;

enterpoint.y = 2;

finalpoint.x = 4;

finalpoint.y = 5;

//初始化棧

mystackinit(s);

//開始走了

mazegetshortpath(enterpoint, s, &maze);

system("pause");

return 0;

}

結果為:

C語言 迷宮(棧實現)

problem i 迷宮 全部 自己編寫 description 編寫乙個程式求解迷宮問題。迷宮是乙個n行m列的矩陣,其中 0 表示無障礙,1 表示有障礙。設入口為 1,1 出口為 n,m 每次移動只能從乙個無障礙的單元移到其周圍4個方向上任一無障礙的單元。若該迷宮存在一條從入口到出口的路徑,則輸出...

棧實現迷宮(c語言)

利用棧實現迷宮問題,1 輸入迷宮的大小m行n列,兩者為整數。2 由隨機數產生0或1,建立迷宮。3 輸出資料。4 首先輸出迷宮,在列印由入口到出口的入線。如無通道,則列印出無。include include include include define maxsize 100 define row 6...

棧實現迷宮求解問題

總體感觸是 不要著急,一步一步來,問題很容易解決的。首先是要實現乙個迷宮的地圖。明確如何儲存地圖,用vector實現二維陣列,每個元素代表地圖的乙個格仔。需要儲存哪些資訊。一張地圖的某乙個方格需要標示 能否通過,是否走過了。94 struct point 位置資訊可用postype儲存。就是 str...