【数据结构】用栈实现迷宫
发布时间:2020-12-15 06:00:01 所属栏目:安全 来源:网络整理
导读:#include iostreamusing namespace std;#define N 10#include stackstruct pos{ int _row;// 行 int _col;// 列};bool cheakstep(pos a){ if(a._col -1||a._col N-1|| a._row -1||a._row N-1) { return true ; } return false ;}bool IsPath(int arr[][N],po
#include <iostream> using namespace std; #define N 10 #include <stack> struct pos { int _row;// 行 int _col;// 列 }; bool cheakstep(pos a) { if(a._col > -1||a._col < N-1|| a._row > -1||a._row < N-1) { return true ; } return false ; } bool IsPath(int arr[][N],pos nowloction,stack<pos>& s) { pos tmp = nowloction; //入栈标记 栈不为空 s.push (nowloction); arr[tmp._row][tmp._col] = 2; while(!s.empty ()) { //shang pos now = s.top (); if(now._row == N-1) { return true ; } now._row -=1; if(cheakstep(now)==true && arr[now._row][now._col]==0) { s.push (now); arr[now._row ][now._col ]=2; continue; } //you now = s.top (); now._col +=1; if(cheakstep(now)==true && arr[now._row][now._col]==0) { s.push (now); arr[now._row ][now._col ]=2; continue; } //xia now = s.top (); now._row +=1; if(cheakstep(now)==true && arr[now._row][now._col]==0) { s.push (now); arr[now._row ][now._col ]=2; continue; } //zuo now = s.top (); now._col -=1; if(cheakstep(now)==true && arr[now._row][now._col]==0) { s.push (now); arr[now._row ][now._col ]=2; continue; } else { now = s.top (); arr[now._row ][now._col ] = 3; s.pop (); } } return false ; } int main() { //定义一个二维数组存放迷宫 1表示墙0表示路 //定义一个栈存放路径 //定义一个入口地址 int arr[N][N]={ 1,1,}; pos entry = {2,0}; stack<pos> path; bool ret = IsPath(arr,entry,path); if(ret == true ) { cout<< "走出迷宫"<<endl; } else cout<< "没有走出迷宫"<<endl; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { cout<<arr[i][j]; } cout<<endl; } cout<<endl; return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |