您的位置:首页 > 理论基础 > 数据结构算法

迷宫解法之栈/队列的解法

2017-08-04 23:09 162 查看
以下是栈

#include<iostream>
#include<stack>
using namespace std;
int a[10][12] = { 1,1,1,1,1,1,1,1,1,1,1,1,
1,0,0,0,1,1,1,1,1,1,1,1,
1,1,1,0,1,1,0,0,0,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,0,0,0,0,1,1,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,1,1,1,0,1,1,0,1,1,
1,1,0,0,0,0,0,0,1,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1};
class Coordinate
{
public:
int x;
int y;
};
int main(void)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<12;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
Coordinate start;
cout<<"输入起点";
cin>>start.x>>start.y;
Coordinate end;
cout<<"输入终点";
cin>>end.x>>end.y;
stack<Coordinate>s;
s.push(start);
bool flag=true;
while(!s.empty()&&flag)
{
a[start.x][start.y]=3;
if(a[start.x-1][start.y]==0)
{
start.x-=1;
s.push(start);
a[start.x][start.y]=-1;
}
else if(a[start.x][start.y-1]==0)
{
start.y-=1;
s.push(start);
a[start.x][start.y]=3;
}
else if(a[start.x][start.y+1]==0)
{
start.y+=1;
s.push(start);
a[start.x][start.y]=3;
}
else if(a[start.x+1][start.y]==0)
{
start.x+=1;
s.push(start);
a[start.x][start.y]=3;
}
else
{
a[start.x][start.y]=3;
start=s.top();
s.pop();
}
if(start.x==end.x&&start.y==end.y)
{
flag=false;
break;
}
}
for(int i=0;i<10;i++)
{
for(int j=0;j<12;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}



以下是队列
#include<iostream>
#include<queue>
using namespace std;
int a[10][12] = { 1,1,1,1,1,1,1,1,1,1,1,1,
1,0,0,0,1,1,1,1,1,1,1,1,
1,1,1,0,1,1,0,0,0,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,0,0,0,0,1,1,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,
1,1,1,1,1,1,0,1,1,0,1,1,
1,1,0,0,0,0,0,0,1,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1};
class Coordinate
{
public:
int x;
int y;
int pre;
};
int main(void)
{
int x,y;
for(int i=0;i<10;i++)
{
for(int j=0;j<12;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
int startx,starty,endx,endy;
int rear=-1;
int front=-1;
Coordinate s[100000];
rear++;
Coordinate start;
cout<<"输入起点";
cin>>startx>>starty;
Coordinate end;
cout<<"输入终点";
cin>>endx>>endy;
s[rear].x=startx;
s[rear].y=starty;
a[startx][starty]=-1;
s[rear].pre=-1;
bool flag=true;
while(front<=rear&&flag)
{
front++;
if(s[front].x==endx&&s[front].y==endy)
{
flag=false;
x=s[front].x;y=s[front].y;
a[x][y]=3;
int h=front;
while(s[h].pre!=-1)
{
int g=s[h].pre;
x=s[g].x;
y=s[g].y;
a[x][y]=3;
h=g;
}
}
for(int direction=0;direction<4;direction++)
{
switch(direction)
{
case 0:x=s[front].x;y=s[front].y-1;break;//上
case 1:x=s[front].x;y=s[front].y+1;break;//下
case 2:x=s[front].x-1;y=s[front].y;break;//左
case 3:x=s[front].x+1;y=s[front].y;break;//右
}
if(a[x][y]==0)
{
rear++;
s[rear].x=x;
s[rear].y=y;
s[rear].pre=front;
}
}
}
for(int i=0;i<10;i++)
{
for(int j=0;j<12;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 队列