stack.h------------------------------------------------
#include<iostream> struct locate { int x; int y; }; class stacknode { friend class stack; public: locate t; stacknode* link; }; class stack { public: stack(); bool isempty(){return (top==NULL);} void insert(locate x); bool pop(locate& x); bool gettop(locate& x); ~stack(); private: stacknode* top; }; stack::stack() { top=NULL; } stack::~stack() { stacknode* t; while(top!=NULL) { t=top; top=top->link; delete t; } } void stack::insert(locate x) { if (top==NULL) { top=new stacknode; top->t=x; top->link=NULL; return; } else { stacknode* t=new stacknode; t->t=x; t->link=top; top=t; } } bool stack::pop(locate& x) { if (top==NULL) { return false; } else { stacknode* t=top; top=top->link; locate x=t->t; delete t; return true; } } bool stack::gettop(locate& x) { if (top==NULL) { return false; } else { x=top->t; return true; } }
maze.cpp--------------------------
#include "stack.h" #define M 5 #define N 22 int maze[M+2][N+2]= { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1, 1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, 1,0,1,1,0,0,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1, 1,1,1,0,1,1,0,1,1,0,1,1,0,0,0,0,1,1,1,1,1,0,1,1, 1,0,0,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }; locate move[8]={{1,0},{1,1},{0,1},{-1,-1},{1,-1},{-1,0},{0,-1},{-1,1}}; void main() { stack m; locate a; a.x=1; a.y=1; m.insert(a); maze[a.x][a.y]=0; while(!(a.x==M&&a.y==N)) { int i; for ( i=0;i<8;i++) { locate c; m.gettop(c); c.x=c.x+move[i].x; c.y=c.y+move[i].y; if (maze[c.x][c.y]==1) { continue; } else { m.insert(c); a.x=c.x; a.y=c.y; maze[a.x][a.y]=1; break; } } if (i==8) { if (m.isempty()==true) { std::cout<<"无输出"; system("pause"); return; } m.pop(a); m.gettop(a); } } while (m.isempty()!=true) { m.gettop(a); std::cout<<a.x<<","<<a.y<<" "; m.pop(a); } system("pause"); }