迷宮尋路C++代碼

xxy220543 9年前發布 | 23K 次閱讀 OPEN 代碼 C/C++開發

 // 迷宮.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; } </pre>

 本文由用戶 xxy220543 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!