queue.h-------------
#include<iostream> struct location { int x; int y; }; struct Node { location data; Node* t; }; class LinkedQueue { // FIFO对象 public: LinkedQueue() {front = rear = NULL;} // 构造函数 ~LinkedQueue(); // 析构函数 bool IsEmpty() const {return ((front) ? false : true);} //location First() const; // 返回第一个元素 //location Last() const; // 返回最后一个元素 void Add(const location); void Delete(location& x); Node *front; // 指向第一个节点 Node *rear; //指向最后一个节点 } ; LinkedQueue::~LinkedQueue() { while(front!=NULL) { Node* m=front; front=front->t; delete m; } } //location LinkedQueue::First()const //{ // if (IsEmpty()) // { // return -1,-1; // } // else{return front->data;} //} // //location LinkedQueue::Last()const //{ // if (IsEmpty()) // { // return -1; // } // return rear->data; //} void LinkedQueue::Add(const location x) { if (IsEmpty()) { front=new Node; front->data=x; front->t=NULL; rear=front; } else { Node* p=new Node; p->data=x; p->t=NULL; rear->t=p; rear=p; } } void LinkedQueue::Delete(location& x) { x=front->data; Node* p=front; front=front->t; delete p; }
maze.cpp---------------
#include "queue.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 }; location move[8]={{1,0},{1,1},{0,1},{-1,-1},{1,-1},{-1,0},{0,-1},{-1,1}}; void main() { location start={1,1}; location end={5,22}; location t=start; location x; LinkedQueue sd; maze[start.x][start.y]=2; int count =0; sd.Add(start); while(count==0&&sd.IsEmpty()==false) { sd.Delete(t); for (int i=0;i<8;i++) { x.x=t.x+move[i].x; x.y=t.y+move[i].y; if (maze[x.x][x.y]==0&&x.x!=5&&x.y!=22) { maze[x.x][x.y]=maze[t.x][t.y]+1; sd.Add(x); } else if(x.x==5&&x.y==22) { maze[x.x][x.y]=maze[t.x][t.y]+1; count++; break; } } }; if (sd.IsEmpty()==true&&count==0) { std::cout<<"无解"; } else { int m=maze[end.x][end.y]; location* getpath=new location[m-2]; location t={end.x,end.y}; location mj; int out; for (int x=m-3;x>=0;x--) { for (int i=0;i<8;i++) { mj.x=t.x+move[i].x; mj.y=t.y+move[i].y; if (maze[mj.x][mj.y]==m-1) { m--; t.x=mj.x; t.y=mj.y; getpath[x]=mj; std::cout<<mj.x<<","<<mj.y<<" "; break; } } } } system("pause"); }