实现简单的迷宫
? 我們知道棧的特點是:后進先出(First In Last Out);也就是說只能在棧的尾部進
行壓棧和出棧,而且出棧的時候只能從最后一個數據開始。
? 所以我們利用棧這個特點,來實現這個迷宮。在這之中我們要采用“回溯”的方法去處理當遇到路徑不通的情況。
? 原理:每找到一個通路,就將這個數據壓棧,這樣當前位置的上一個位置就位于棧的頂部,假如當前位置的上下左右都找不到通路的時候,就開始回溯,也就是開始從來的路往回走,而之前走過的路都存在棧里面,所以只需要一個一個的Pop就能依次往回退,每退一次,就尋找上下左右有沒有通路,如果找到通路就繼續往下走,并壓棧,直到走出整個迷宮。
#define?_CRT_SECURE_NO_WARNINGS?1 #include"MazeMap.h" #include<stdio.h>?void?test() {int?a[N][N];GetMaze((int*)a,?N);stack<pos>?paths;pos?entry?=?{?2,?0?};cout?<<?searchpath((int*)a,?10,?entry,?paths)<<endl;display((int*)a,?N); } int?main() {test();system("pause");return?0; }#pragma?once #include<stack> #include<assert.h>#define?N??10 #include<iostream> using?namespace?std;struct?pos {int?_row;int?_col; }; void?GetMaze(int*?a,?int?n)????? {assert(a);FILE*?fout?=?fopen("C:\\maze.txt",?"r");assert(fout);for?(int?i?=?0;?i?<?n;?i++){for?(int?j?=?0;?j?<?n;){char?ch?=?fgetc(fout);if?(ch?==?'1'?||?ch?==?'0')?//只讀有效的字符,遇空格不轉換{a[i?*?n?+?j]?=?ch?-?'0';j++;}else{continue;}}}fclose(fout); } bool?CheckisAccess(int?*a,?int?n,?const?pos&?next)//檢查當前的路徑是否通行 {int?row?=?next._row;int?col?=?next._col;if?(row?>=?0?&&?row?<?n&&col?>=?0?&&?col?<?n&&a[next._row*n?+?next._col]?==?0){return?true;}else{return?false;} } bool?searchpath(int*?a,?int?n,?pos?entry,?stack<pos>&?paths) {assert(a);paths.push(entry);?????//將入口地址(坐標)push到棧中while?(!paths.empty())??//如果棧為空,就沒找到出口{pos?cur?=?paths.top();?????a[cur._row*n?+?cur._col]?=?2;??//將走過的路徑置為2if?(cur._row?==?n?-?1){return?true;}pos?next?=?cur;?????//先將cur賦給next??為了下面如果next改變后不滿足,?????????????????next._row--;//上??????????????????????????if?(CheckisAccess(a,?n,?next)){cur?=?next;paths.push(cur);continue;}next?=?cur;next._col++;//右if?(CheckisAccess(a,?n,?next)){cur?=?next;paths.push(cur);continue;}next?=?cur;next._row++;//下if?(CheckisAccess(a,?n,?next)){cur?=?next;paths.push(cur);continue;}next?=?cur;next._col--;//?左if?(CheckisAccess(a,?n,?next)){cur?=?next;paths.push(cur);continue;}next?=?cur;paths.pop();?????//如果遇到不通(在此即四個方向都不為0)然后,讓棧中保存}??????????????????????????????的坐標pop(即往回倒)重復試探四個方向?直到找到另一return?false;???????????????????條可通路徑; } void?display(int*?a,?int?n)????//打印 {for?(int?i?=?0;?i?<?n;?i++){for?(int?j?=?0;?j?<?n;?j++){cout?<<?a[i*n?+?j]?<<?"?";}cout?<<?endl;}}? ?至此,一個簡單的迷宮就完成了,以上左邊的圖就是開始的迷宮。右邊的圖是結果。最終,每次走過的地方都被標志成2.
轉載于:https://blog.51cto.com/10738432/1762711
總結
- 上一篇: HDU 2393 Higher Math
- 下一篇: 中项笔记(六)