巧用棧結構實現迷宮遊戲
阿新 • • 發佈:2019-02-15
當我們學習了棧這種資料結構以後,我們就可以利用棧來實現一個簡單的迷宮遊戲 ,首先我們給出迷宮的地圖,這是一個二維陣列。
{0,0,1,0,0,0,0,0,0,0},
{0,0,1,1,1,1,1,0,0,0},
{0,0,0,0,0,0,1,0,0,0},
{0,0,0,1,0,0,1,0,0,0},
{0,0,0,1,1,1,1,0,0,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,1,1,1,1,0,0,0},
{0,0,0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,1,0,0,0},
我們從陣列的(9,6)這個位置開始走,直到(0,2)這個位置走到出口。下面是實現的程式碼
struct Seat { Seat(int x, int y) :_x(x) , _y(y) {} int _x; int _y; }; class Maze { public: bool IsPass(Seat& Pcur) { if (IsExit(Pcur)) return true; if (maze[Pcur._x][Pcur._y] == 1) return true; return false; } bool IsExit(const Seat& s) { if ((s._x < 0 || s._x >= row || s._y < 0 || s._y >= col)) { return true; } return false; } bool GOMaze(Seat& Enter) { //入口非法 if (!IsPass(Enter)) { cout << "非法入口" << endl; return false; } //入口可以走,先走這一步 stack<Seat> s; s.push(Enter); while (!s.empty()) { Seat cur = s.top(); if (IsExit(cur)) { return true; } maze[cur._x][cur._y] = 2; //先向上走 Seat up(cur); up._x -= 1; if (IsPass(up)) { s.push(up); continue; } //向左左 Seat left(cur); left._y -= 1; if (IsPass(left)) { s.push(left); continue; } //向右走 Seat right(cur); right._y += 1; if (IsPass(right)) { s.push(right); continue; } //向下走 Seat down(cur); down._x += 1; if (IsPass(down)) { s.push(down); continue; } maze[cur._x][cur._y] = 3; s.pop(); } return false; } Maze(int* m, int r, int c) :row(r) ,col(c) { maze.resize(row); for (int i = 0; i < row; i++) { maze[i].resize(col); for (int j = 0; j < col; j++) { maze[i][j] = m[i*col+j]; } } } void printMaze() { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << maze[i][j] << " "; } cout << endl; } cout << endl; } private: vector<vector<int>> maze; int row; int col; };
我們將每走過的一步路都標記成2並進行壓棧操作,當走到死衚衕時,例如這裡的(3,3)這種情況,我們將其標記成3,然後進行出棧操作,回彈到上一個路口,選擇其他路走,這時候就可以找到出口。
這是一開始的地圖,接下來我們開始走迷宮。
成功完成了一個迷宮演算法,當然這只是迷宮的一個簡單情況,我們還可以將迷宮地圖放入一個檔案中,然後從檔案中讀取迷宮的地圖,讀者可以自行實現。