题目链接:这里哈哈~
#include<cstdio> #include<iostream> #include<cstring> using namespace std; int sx,sy,ex,ey,h,w; int mp[30][30]; int minn(int x,int y) { return x<y?x:y; } int dfs(int x,int y,int step) { if(step>10) return 1000000; int i=1,ret=1000000; if(x+i<h && mp[x+i][y]!=1) { while(x+i<h && !mp[x+i][y]) i++; if(x+i<h) { if(mp[x+i][y]==3) return step; int tmp=mp[x+i][y]; mp[x+i][y]=0; ret=minn(ret,dfs(x+i-1,y,step+1)); mp[x+i][y]=tmp; } } i=1; if(y+i<w && mp[x][y+i]!=1) { while(y+i<w && !mp[x][y+i]) i++; if(y+i<w) { if(mp[x][y+i]==3) return step; int tmp=mp[x][y+i]; mp[x][y+i]=0; ret=minn(ret,dfs(x,y+i-1,step+1)); mp[x][y+i]=tmp; } } i=1; if(x-i>=0 && mp[x-i][y]!=1) { while(x-i>=0 && !mp[x-i][y]) i++; if(x-i>=0) { if(mp[x-i][y]==3) return step; int tmp=mp[x-i][y]; mp[x-i][y]=0; ret=minn(ret,dfs(x-i+1,y,step+1)); mp[x-i][y]=tmp; } } i=1; if(y-i>=0 && mp[x][y-i]!=1) { while(y-i>=0 && !mp[x][y-i]) i++; if(y-i>=0) { if(mp[x][y-i]==3) return step; int tmp=mp[x][y-i]; mp[x][y-i]=0; ret=minn(ret,dfs(x,y-i+1,step+1)); mp[x][y-i]=tmp; } } return ret; } int main() { while(scanf("%d%d",&w,&h)!=EOF) { if(w==0 && h==0) break; memset(mp,0,sizeof(mp)); for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { scanf("%d",&mp[i][j]); if(mp[i][j]==2) { sx=i; sy=j; mp[i][j]=0; } if(mp[i][j]==3) { ex=i; ey=j; } } } int ans=dfs(sx,sy,1); if(ans!=1000000) printf("%d\n",ans); else printf("-1\n"); } return 0; } /* 18 2 1 1 0 1 0 1 1 0 1 0 0 3 0 0 1 0 1 0 0 0 0 1 0 1 0 1 1 2 1 1 0 1 0 0 1 0 -1 14 6 0 0 1 0 0 0 0 1 1 0 1 1 1 0 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 0 2 1 1 0 0 1 0 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 0 0 0 1 0 1 0 0 1 0 0 1 0 0 0 0 3 -1 */