直接上代码,不明白的欢迎评论,看到必回!!!
#include<iostream>
#include<stdio.h>
#define max 100
using namespace std;
int mg[100][100];
typedef struct{
int x,y,di;
}box;
typedef struct{
box data[max];
int top;
}St;
bool mgpath(int xi,int yi,int xe,int ye){
int x,y,di,find;
St st;
st.top=0;
st.data[st.top].x=xi;
st.data[st.top].y=yi;
st.data[st.top].di=-1;
mg[xi][yi]=-1;
while(st.top>-1){
x=st.data[st.top].x;
y=st.data[st.top].y;
di=st.data[st.top].di;
if(x==xe&&y==ye){
for(int k=0;k<=st.top;k++){
printf("\t(%d, %d)",st.data[k].x,st.data[k].y);
if((k+1)%5==0)
cout<<endl;
}
return true;
}
find=0;
while(find==0&&di<4){
di++;
switch(di){
case 0:
x=st.data[st.top].x-1;
y=st.data[st.top].y;
break;
case 1:
x=st.data[st.top].x;
y=st.data[st.top].y+1;
break;
case 2:
x=st.data[st.top].x+1;
y=st.data[st.top].y;
break;
case 3:
x=st.data[st.top].x;
y=st.data[st.top].y-1;
break;
}
if(mg[x][y]==0)
find=1;
}
if(find==1){
st.data[st.top].di=di;
st.top++;
st.data[st.top].x=x;
st.data[st.top].y=y;
st.data[st.top].di=-1;
mg[x][y]=-1;
}
else{
mg[st.data[st.top].x][st.data[st.top].y]=0;
st.top--;
}
}
return false;
}
int main(){
int x,y;
cin>>x>>y;
int i,j;
for(i=0;i<x;i++)
for(j=0;j<y;j++)
cin>>mg[i][j];
if(!mgpath(1,1,x-2,y-2)){
cout<<"no way";
}
return 0;
}