C++超迷你迷宮
#include <iostream>include <stack>
using namespace std;
define SIZE 10
typedef int Array[SIZE][SIZE];
struct Pos { int x; int y; Pos(){} Pos(int val1,int val2):x(val1),y(val2){} };//記錄位置x,y,相當于記錄的相應位置坐標。 struct Man { Pos pos; };
class Maze { public: Maze(int a[][SIZE]) { for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) {
arr[i][j] = a[i][j]; } } }void Printf() { for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) { cout<<arr[i][j]<<" "; } cout<<endl; } }
void InitGrial(const Pos &start,const Pos &end) { Man man; man.pos.x = start.x; man.pos.y = start.y; // man.kind = RIGHT; stack<Man> st; stack<Man> sh; st.push(man);//此處才把起始位置放進棧st里面。 Postion(man);//記住man走過的足跡. while(!st.empty()) { Pos NewPos; Man man = st.top(); if (InitNewPos(NewPos,man)) {
Man NewMan; NewMan.pos = NewPos; st.push(NewMan); Postion(NewMan); if(NewMan.pos.x==end.x && NewMan.pos.y==end.y)break; } else { sh.push(st.top()); st.pop(); } }
while(!sh.empty()) { Man man = sh.top(); arr[man.pos.x][man.pos.y]=0; sh.pop(); } } bool InitNewPos(Pos &pos,Man &man) { if(arr[man.pos.x][man.pos.y+1]==0) { pos.x=man.pos.x; pos.y=man.pos.y+1; return true; } if(arr[man.pos.x+1][man.pos.y]==0) { pos.x=man.pos.x+1; pos.y=man.pos.y; return true; } if(arr[man.pos.x][man.pos.y-1]==0) { pos.y = man.pos.y-1; pos.x = man.pos.x; return true; } if(arr[man.pos.x-1][man.pos.y]==0) { pos.x = man.pos.x-1; pos.y = man.pos.y; return true;
} return false; } void Postion(Man &man) { arr[man.pos.x][man.pos.y]=2; } private: Array arr; };int main() { int a[][10]= {1,0,1,1,1,1,1,1,1,1, 1,0,0,0,0,0,1,1,0,1, 1,0,1,1,1,0,0,1,0,1, 1,0,0,1,1,1,0,0,0,1, 1,1,0,1,1,1,1,0,0,1, 1,1,0,1,1,1,1,1,1,1, 1,1,0,1,1,1,1,1,1,1, 1,1,0,0,0,0,1,1,1,1, 1,1,1,1,1,0,0,0,1,1, 1,1,1,1,1,1,1,0,1,1};
Maze ma(a); Pos start(0,1); Pos end(9,7);//定義開始的位置以及結束的位置。ma.InitGrial(start,end);
//然我們開始吧,實在想不出名字了,Grial是圣杯的意思.
ma.Printf(); return 0;
}</pre>