题目如下:
我自己对着课本写的代码如下(一直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;
}
你上面复制粘贴有问题。我就稍微改下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;
}
}
问答竟然不能修改
int main()
{
int k, n, ha, la, hb, lb;
char ch;
cin >> k;//k组数据
for (int i = 0; i<k ;++i){
cin >> n;//n*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;
}
}