堆栈求迷宫问题

堆栈求迷宫问题 

/*
Name: 堆栈求迷宫问题 
Copyright: 
Author: 
Date: 14/04/17 18:25
Description: 希望以后参考到
*/
#include<iostream>
using namespace std;
typedef struct 
{
int i;
int j;
int di;
}box;
typedef struct
{
box data[50];
int top;
}road;
int mg[5][5]={
{1,1,1,1,1},
{1,0,1,1,1},
{1,0,1,0,1},
{1,1,1,0,1},
{1,1,1,1,1}};
void mapath(int xi,int yi,int m,int n)
{
road s;
int x,y,k;
int find;
int di;
s.top=-1;
s.top++;
s.data[s.top].i=xi;
s.data[s.top].j=yi;
s.data[s.top].di=-1;
mg[xi][yi]=-1;
while(s.top>-1)
{
x=s.data[s.top].i;
y=s.data[s.top].j;
di=s.data[s.top].di;
if(x==m&&y==n)
{
cout<<"路径如下:"<<endl; 
for(k=0;k<=s.top;k++)
cout<<s.data[k].i<< s.data[k].j<<endl;
}
find=0;
while(di<4&&find==0)
{
di++;
switch(di)
{
case 0: x=s.data[s.top].i;y=s.data[s.top].j-1;break;
case 1: x=s.data[s.top].i+1;y=s.data[s.top].j;break;
case 2: x=s.data[s.top].i;y=s.data[s.top].j+1;break;
case 3: x=s.data[s.top].i-1;y=s.data[s.top].j;break;
}
if(mg[x][y]==0)
find=1;
}
if(find==1) //找到下一个可走方块 
{
s.data[s.top].di=di;
s.top++;
s.data[s.top].i=x;
s.data[s.top].j=y;
s.data[s.top].di=-1;
mg[x][y]=-1;
}
else //没有路径可走,则推栈 
{
mg[s.data[s.top].i][s.data[s.top].j]=0;
s.top--;
}
}
cout<<"没有可走的路径"; 
}
int main()
{
mapath(1,1,3,3);
return 0;
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/ye_se_cong_cong/article/details/73302498
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞