简单的DFS。一开始把DFS里面的一个变量弄成 全局变量了,调试了半个小时才发现......
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cstring> 6 7 using namespace std; 8 9 int MinStep; 10 11 int map[25][25]; 12 13 int h,w; 14 15 struct Point 16 { 17 int h,w; 18 }sp,ep,np; 19 20 int jh[] = { 0,-1, 1, 0}; 21 int jw[] = {-1, 0, 0, 1}; 22 23 bool check(Point tp) 24 { 25 if(tp.h >= 1 && tp.h <= h && tp.w >= 1 && tp.w <= w && map[tp.h][tp.w] != 1 && map[tp.h][tp.w] != 3) 26 return true; 27 return false; 28 } 29 30 void dfs(int nh,int nw,int ans) 31 { 32 33 if(ans > 10) 34 { 35 return ; 36 } 37 if(nh == ep.h && nw == ep.w) 38 { 39 if(ans < MinStep) 40 MinStep = ans; 41 return ; 42 } 43 44 int i; 45 Point tp; 46 47 for(i = 0;i < 4; i++) 48 { 49 tp.h = nh; 50 tp.w = nw; 51 while(check(tp)) 52 { 53 tp.h += jh[i]; 54 tp.w += jw[i]; 55 } 56 if(tp.h >= 1 && tp.h <= h && tp.w >= 1 && tp.w <= w && map[tp.h][tp.w] == 3) 57 { 58 // printf("nh = %d nw = %d tp.h = %d tp.w = %d ans = %d### ",nh,nw,tp.h,tp.w,ans); 59 dfs(tp.h,tp.w,ans+1); 60 } 61 else if(tp.h >= 1 && tp.h <= h && tp.w >= 1 && tp.w <= w && map[tp.h][tp.w] == 1) 62 { 63 tp.h -= jh[i]; 64 tp.w -= jw[i]; 65 if(tp.h != nh || tp.w != nw) 66 { 67 // printf("nh = %d nw = %d tp.h = %d tp.w = %d ans = %d*** ",nh,nw,tp.h,tp.w,ans); 68 map[tp.h + jh[i]][tp.w + jw[i]] = 0; 69 dfs(tp.h,tp.w,ans+1); 70 map[tp.h + jh[i]][tp.w + jw[i]] = 1; 71 } 72 } 73 } 74 } 75 76 int main() 77 { 78 79 int i,j; 80 while(scanf("%d %d",&w,&h) && (w || h)) 81 { 82 MinStep = 1000; 83 for(i = 1;i <= h; ++i) 84 for(j = 1;j <= w; ++j) 85 { 86 scanf("%d",&map[i][j]); 87 if(map[i][j] == 2) 88 { 89 sp.h = i; 90 sp.w = j; 91 } 92 else if(map[i][j] == 3) 93 { 94 ep.h = i; 95 ep.w = j; 96 } 97 } 98 dfs(sp.h,sp.w,0); 99 if(MinStep == 1000) 100 printf("-1 "); 101 else printf("%d ",MinStep); 102 } 103 return 0; 104 }