迷宫寻路C++代码

xxy220543 9年前

 // 迷宫.cpp : 定义控制台应用程序的入口点。   //     #include "stdafx.h"   #include<iostream>   #include<stack>   using namespace std;       struct pos{   int x;   int y;        };   pos& operator+=(pos&p1,pos&p2){   p1.x+=p2.x;   p1.y+=p2.y;   return p1;   }   struct movpos{   int order;//路径中的序号   pos  p;//路径中的位置       };   movpos currentmovpos;   pos currentpos;   stack<movpos>  S;     int visited[10][10]={0};   pos vect[4]={   {1,0},   {0,1},   {-1,0},   {0,-1}   };   int count1=1 ;   bool flag=false;   void searchPath(pos& start,pos& end1,int a[10][10]){      if(count1==1){    visited[start.y][start.x]=1;    currentmovpos.order=count1;    currentmovpos.p=start;    S.push(currentmovpos);   }   for(int i=0;i<4;i++){   if(flag) break;   if((a[start.y+vect[i].y][start.x+vect[i].x]==1)&&   (!visited[start.y+vect[i].y][start.x+vect[i].x]))   {   start+=vect[i];//移动到下一个位置   visited[start.y][start.x]=1;//设为到过            count1++;   currentmovpos.order=count1;   currentmovpos.p=start;   S.push(currentmovpos);       if((start.x==end1.x)&&(start.y==end1.y)){    flag=true;   break;  }   else{searchPath(start,end1,a);}   }   else{     if(i==3){    S.pop();   currentmovpos=S.top();     start=currentmovpos.p;   count1--;   }     }       }//for     }     int main()   {   int a[10][10]={     //0,1,2,3,4,5,6,7,8,9   {0,0,0,0,0,0,0,0,0,0},//0   {0,1,1,0,1,1,1,0,1,0},//1   {0,1,1,0,1,1,1,0,1,0},//2   {0,1,1,1,1,0,0,1,1,0},//3   {0,1,0,0,0,1,1,1,1,0},//4   {0,1,1,1,0,1,1,1,1,0},//5   {0,1,0,1,1,1,0,1,1,0},//6   {0,1,0,0,0,1,0,0,1,0},//7   {0,0,1,1,1,1,1,1,1,0},//8   {0,0,0,0,0,0,0,0,0,0}//9   };    stack<movpos> q;   pos start={1,1};       pos end1={8,8};   searchPath(start,end1,a);   while(!S.empty()){   q.push(S.top());      S.pop();   }   while(!q.empty()){        cout<<"顺序"<<q.top().order<<"  位置 x="<<q.top().p.x<<" y="<<q.top().p.y<<endl;     q.pop();    }   return 0;   }