啊哈演算法-解救小哈
阿新 • • 發佈:2021-12-16
#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了半天最後發現是初始的地圖和書上畫的不一樣的邊界= =