入门小学生 2017-03-27 11:03 采纳率: 0%
浏览 863
已结题

数据结构栈的迷宫问题,一直是Time Limit Exceeded ,求大神帮助

题目如下:图片说明

我自己对着课本写的代码如下(一直Time Limit Exceeded ):

#include
#define MaxSize 110
char mg[MaxSize][MaxSize];
typedef struct {
int i;
int j;
int di;
}Box;
typedef struct {
Box data[MaxSize];
int top;
}StType;
bool mgpath(int xi,int yi,int xe,int ye);
using namespace std;
int main()
{
int k,n,ha,la,hb,lb;
char ch;
cin>>k;
for(int i=0;i {
cin>>n;
for(int h=0;h<n;h++)

                    for(int l=0;l<n;l++)

                            cin>>mg[h][l];
    cin>>ha>>la>>hb>>lb;
    if(mgpath(ha,la,hb,lb))
        cout<<"YES"<<endl;
    else    cout<<"NO"<<endl;
}

}
bool mgpath(int xi,int yi,int xe,int ye)
{
int i,j,k,di,find;
StType st;
st.top=-1;
st.top++;
st.data[st.top].i=xi;
st.data[st.top].j=yi;
st.data[st.top].di=-1;
mg[xi][yi]='*';
while(st.top>-1)
{
i=st.data[st.top].i;
j=st.data[st.top].j;
di=st.data[st.top].di;
if(i==xe&&j==ye)
return true;
find=0;
while(di<4&&find==0)
{
di++;
switch(di)
{
case 0: i=st.data[st.top].i-1;j=st.data[st.top].j;break;
case 1: i=st.data[st.top].i;j=st.data[st.top].j+1;break;
case 2: i=st.data[st.top].i+1;j=st.data[st.top].j;break;
case 3: i=st.data[st.top].i;j=st.data[st.top].j-1;break;
}
if(mg[i][j]=='.') find=1;
}
if(find==1)
{
st.data[st.top++].di=di;
st.data[st.top].i=i;
st.data[st.top].j=j;
st.data[st.top].di=-1;
mg[i][j]='*';
}
else
{
mg[st.data[st.top].i][st.data[st.top].j]='.';
st.top--;
}
}
return false;
}

  • 写回答

2条回答 默认 最新

  • Ousinkou 2017-03-27 11:33
    关注

    你上面复制粘贴有问题。我就稍微改下main函数,然后运行是正确的,没有发现你说的Time Limit Exceeded问题
    int main()
    {
    int k, n, ha, la, hb, lb;
    char ch;
    cin >> k;//k组数据
    for (int i = 0; i cin >> n;//n*n矩阵
    for (int h = 0; h for (int l = 0; l cin >> mg[h][l];//保存在该区域中

            cin >> ha >> la >> hb >> lb;
            if (mgpath(ha,la,hb,lb))
                cout << "YES"<< endl;
            else 
                cout <<"No" <<endl;
    }
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路