我們知道棧的特點是:後進先出(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; //將走過的路徑置爲2 if (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.