栈应用之简单迷宫问题(C语言版)
生活随笔
收集整理的這篇文章主要介紹了
栈应用之简单迷宫问题(C语言版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
迷宮在這兒——–>(用二維數組實現)
棧的應用有很多,前面解決了括號問題和后綴表達式問題,迷宮便可以解決了!!
迷宮的解題思路有點繞,并且其棧的結構也有所改變!但是本次解決迷宮仍然用的普通的棧
首先:迷宮如下(1表示通路,0表示非通路)
0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 1 0 1 1 0 0 1 0 0 0解題思路:
迷宮結構,以及位置結構
typedef struct Position //位置結構體 {int _x;int _y; }Position;#define MAX_ROW 6 #define MAX_COL 6 typedef struct Maze //迷宮結構體 {int _map[MAX_ROW][MAX_COL]; //一張地圖}Maze;一些輔助判斷函數
//初始化位置 void PositionInit(Position* pos, int row, int col) {assert(pos);pos->_x = row;pos->_y = col; } //初始化迷宮 void MazeInit(Maze* m, int map[][MAX_COL]) {assert(m); //參數檢測int i = 0, j = 0;for (i = 0; i < MAX_ROW; i++) //遍歷賦值 {for (j = 0; j < MAX_COL; ++j){m->_map[i][j] = map[i][j];}} } //打印迷宮 void MazePrint(Maze* m, int map[][MAX_COL]) {assert(m); //參數檢測int i = 0, j = 0;for (i = 0; i < MAX_ROW; ++i) //遍歷打印 {for (j = 0; j < MAX_COL; ++j){printf("%d ", m->_map[i][j]);}printf("\n");} } //判斷是否為合理入口 int IsValidEntry(Maze* m, Position now) {assert(m); //參數檢測if (now._x == 0 || now._x == MAX_ROW - 1 || //入口合理的條件(四個)now._y == 0 || now._y == MAX_COL - 1) {if (m->_map[now._x][now._y] == 1)return 1; } return 0; } //判斷是否為通路 int IsPass(Maze* m, Position next) {if (m->_map[next._x][next._y] == 1) //下一個位置元素為1,即為通路return 1;return 0; } //判斷是否為出口 int IsExit(Maze* m, Position now, Position entry) {if (now._x == 0 || now._x == MAX_ROW - 1 || //入口合理的條件(四個)now._y == 0 || now._y == MAX_COL - 1 ) //出口和入口的條件一致{if (now._x != entry._x && now._y != entry._y) //出口不能和入口是同一個return 1;}return 0; }劃重點!!!—->走迷宮函數(循環法)
//走迷宮(循環法)(簡單迷宮) void PassMaze(Maze* m, Position entry, Stack* s) {assert(m); //參數檢測Position _now, _next; //創建當前位置和下一個位置if (!IsValidEntry(m, entry)) //判斷入口是否合理 {printf("迷宮入口不合理!! \n");return; }StackPush(s, (entry._x * MAX_ROW) + entry._y); //入棧入口 _now = entry; while (!IsExit(m, _now, entry)) //當前步不是出口--->進入循環 {_now._x = StackTop(s) / MAX_COL; //將當前步改為棧頂位置_now._y = StackTop(s) % MAX_COL;m->_map[_now._x][_now._y] = 2;if (IsExit(m, _now, entry)) //判斷是否出口return;//往上走_next = _now; //找到下一步,判斷是否為通路,是則入棧,并且該位置元素改為2_next._x -= 1;if (IsPass(m, _next)){StackPush(s, (_next._x * MAX_ROW) + _next._y);m->_map[_next._x][_next._y] = 2;continue;}//往左走_next = _now;_next._y -= 1;if (IsPass(m, _next)){StackPush(s, (_next._x * MAX_ROW) + _next._y);m->_map[_next._x][_next._y] = 2;continue;}//往右走_next = _now;_next._y += 1;if (IsPass(m, _next)){StackPush(s, (_next._x * MAX_ROW) + _next._y);m->_map[_next._x][_next._y] = 2;continue;}//往下走_next = _now;_next._x += 1;if (IsPass(m, _next)){StackPush(s, (_next._x * MAX_ROW) + _next._y);m->_map[_next._x][_next._y] = 2;continue;}StackPop(s); //走到死胡同,該位置是錯誤的,將其出棧,并且將該位置元素改為3m->_map[_now._x][_now._y] = 3; } }測試結果:
另外
1、該迷宮有優化之處!!今后會優化一次!!
2、其他棧應用問題,大家可以看主頁!!!
3、關于棧的基礎操作,附上鏈接:https://blog.csdn.net/code_zx/article/details/80812635
4、謝謝!!!!
總結
以上是生活随笔為你收集整理的栈应用之简单迷宫问题(C语言版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 那些年,你与快递小哥的爱恨情仇...
- 下一篇: c++11新特性介绍