啊哈算法-解救小哈
#include<stdio.h> int a[1005][1005],n,m,n_x,n_y,s_x,s_y,book[1005][1005],min=1005; void find(int x,int y,int step); void go(int x,int y); int main(){ scanf("%d%d",&n,&m); for(int i=0;i<n;i++){ for(int j=0;j<m;j++) scanf("%d",&a[i][j]);//画地图 } scanf("%d%d%d%d",&s_x,&s_y,&n_x,&n_y); find(s_x,s_y,0);//我这里定义的地图边界是0,书上是1,所以初始位置和找的点的位置要-1; printf("%d",min); return 0; } void find(int x,int y,int step){ if(x==n_x && y==n_y){ if(min>step) min=step; return ; } if(x-1>=0 && a[x-1][y]==0 && book[x-1][y]==0){ book[x-1][y]=1; find(x-1,y,step+1); book[x-1][y]=0; } if(x+1<=n-1 && a[x+1][y]==0 && book[x+1][y]==0){ book[x+1][y]=1; find(x+1,y,step+1); book[x+1][y]=0; } if(y-1>=0 && a[x][y-1]==0 && book[x][y-1]==0){ book[x][y-1]=1; find(x,y-1,step+1); book[x][y-1]=0; } if(y+1<=m-1 && a[x][y+1]==0 && book[x][y+1]==0){ book[x][y+1]=1; find(x,y+1,step+1); book[x][y+1]=0; } return ; } /* 测试样例 5 4 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 3 2 输出:7 */
debug了半天最后发现是初始的地图和书上画的不一样的边界= =