這是迷宮回溯的問題,我的測驗資料如圖,還有題目如圖

uj5u.com熱心網友回復:
#include <iostream>#include <queue>
#include <stack>
using namespace std;
struct node
{
int x;
int y;
int per; //指向前一個在aa陣列中的位置
int location;//當前在aa陣列中的位置
node(int ix,int iy,int pe,int lo)
{
x=ix;
y=iy;
per=pe;
location=lo;
}
node(){
}
}aa[30];
bool vis[5][5];
int a[5][5];
int d[4][2]={-1,0,1,0,0,1,0,-1};
stack <node> st;
queue <node> q;
void bfs()
{
while(!q.empty())
q.pop();
while(!st.empty())
st.pop();
q.push(node(0,0,-1,0));
vis[0][0]=1;
aa[0]=q.front();//先將第一個放入陣列中,這個aa陣列里面的位置沒有固定的位置,有per可以確定
int k=1;
while(!q.empty())
{
struct node now=q.front();
q.pop();
int x=now.x;
int y=now.y;
// int per=now.per;
int location=now.location;
for(int i=0;i<4;i++)
{
int dx=x+d[i][0];
int dy=y+d[i][1];
if(dx==4&&dy==4)//滿足時將結果放入堆疊中
{
int t;
st.push(node(dx,dy,location,k)); //終點放入堆疊中
cout<<dx<<" "<<dy<<" "<<location<<" "<<k<<endl;
struct node w;
w=st.top();
while(1)
{
// cout<<w.x<<" "<<w.y<<" "<<w.per<<" "<<w.location<<endl;
int t=w.per;
if(t==-1) //表示已經到起點了
break;
w=aa[t];
st.push(node(w.x,w.y,w.per,w.location));
}
return ;
}
if(dx>=0&&dx<=4&&dy>=0&&dy<=4&&vis[dx][dy]==0&&a[dx][dy]!=1)
{
vis[dx][dy]=1;
q.push(node(dx,dy,location,k));
aa[k]=q.front(); //放到結構體aa陣列中,per,location是記錄位置資訊的
cout <<"k="<<k<<endl;//測驗用的
cout<<aa[k].x<<" "<<aa[k].y<<" "<<aa[k].per<<" "<<aa[k].location<<endl;//測驗用的
k+=1;
}
}
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];
bfs();
while(!st.empty())
{
struct node s=st.top();
cout<<"("<<s.x<<", "<<s.y<<")"<<endl;
st.pop();
}
return 0;
}
uj5u.com熱心網友回復:
這是題目的代碼uj5u.com熱心網友回復:
先把代碼格式化一下吧,這樣子看有點亂
還有,建議你把建構式寫成:
node():x(0),y(0),per(0),location(0){ }
uj5u.com熱心網友回復:
最好自己學會除錯,上一大堆代碼,別人未必有興趣去看。uj5u.com熱心網友回復:
好的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/97391.html
標籤:C++ 語言
上一篇:如何用%s輸出字串。
下一篇:洗掉.exe程式
