深度优先搜索
然后找出最少步数
#include<iostream>
using namespace std;
int maze[5][5];
int tamp[1000][1000][2];//存储
int biaoji [5][5];
int c=0;
int h=0;
int bushu[1000];
int cx[4]={1,0,0,-1};//右下上左
int cy[4]={0,1 ,-1 ,0 };
int ax=0,ay=0,k=0;
int bx=4,by=4;
void walk(int x,int y){
if(x==bx&&y==by)
{ bushu[c]=k;
c++;
}else{
for(int i=0;i<4;++i){
if(maze[x+cx[i]][y+cy[i]]==0&&0<=(x+cx[i])&&(x+cx[i])<=4&&0<=(y+cy[i])&&(y+cy[i])<=4&&biaoji[x+cx[i]][y+cy[i]]==0)
{
tamp[c][k][0]=x;
tamp[c][k][1]=y;
biaoji[x+cx[i]][y+cy[i]]=1;
k++;
walk(x+cx[i],y+cy[i]);
k--;
}
}
}
}
int main(){
for(int i=0;i<5;++i){
for(int j=0;j<5;++j){
cin>>maze[i][j];
}
}
walk(ax,ay);
int min=bushu[0];
for(int i=1;i<c;++i){
if( min<=bushu[i]){}else{
min=bushu[i];
h=i;
}
}
int q=0;
for(int i=bushu[h]-1;i>=0;--i){
if(tamp[h][i][0]==0&&tamp[h][i][0]){
q=i;
break;
}
}
for(int i=0;i<=q;++i){
cout<<"("<<tamp[0][i][0]<<", "<<tamp[0][i][1]<<")"<<endl;
}
for(int i=q+1;i<bushu[h];++i){
cout<<"("<<tamp[h][i][0]<<", "<<tamp[0][i][1]<<")"<<endl;
}
cout<<"("<<4<<", "<<4<<")";
return 0;}