1 #include <iostream> 2 3 using namespace std; 4 5 int w, h; 6 int MAP[41][41]; 7 int sx, sy, ex, ey; 8 int res; 9 int dx[4] = { 10 1, -1, 0, 0 11 }; 12 int dy[4] = { 13 0, 0, 1, -1 14 }; 15 16 int runing(int &x, int &y, int dir) 17 { 18 for(;;) 19 { 20 int nx = x + dx[dir]; 21 int ny = y + dy[dir]; 22 if(nx >= 0 && nx < w && ny >= 0 && ny < h) 23 { 24 if(MAP[ny][nx] == 1) 25 { 26 return 1; 27 } 28 else if(nx == ex && ny == ey) 29 { 30 return 0; 31 } 32 } 33 else 34 { 35 return -1; 36 } 37 x = nx; 38 y = ny; 39 } 40 } 41 42 void dfs(int x, int y, int sum) 43 { 44 int nx, ny; 45 //´óÓÚ10£¬¼ôÖ¦ 46 if(sum > 10) 47 return ; 48 49 50 //Ëĸö·½Ïò½øÐÐËÑÑ° 51 for(int i = 0; i < 4; ++i) 52 { 53 nx = x + dx[i]; 54 ny = y + dy[i]; 55 if(nx >= 0 && nx < w && ny >= 0 && ny < h) 56 { 57 if(MAP[ny][nx] == 1) 58 { 59 continue; 60 } 61 } 62 else 63 continue; 64 nx = x; ny = y; 65 int temp = runing(nx, ny, i); 66 //ÍùÕâ¸ö·½ÏòÅöµ½µÄÊÇǽ 67 if(temp == 1) 68 { 69 MAP[ny+dy[i]][nx+dx[i]] = 0; 70 dfs(nx, ny, sum+1); 71 MAP[ny+dy[i]][nx+dx[i]] = 1; 72 73 } 74 //ÍùÕâ¸ö·½Ïò³ö½çÁË 75 else if(temp == -1) 76 { 77 continue; 78 } 79 //ÍùÕâ¸ö·½Ïòµ½´ïÁËÖÕµã 80 else if(temp == 0) 81 { 82 if(res > sum) 83 res = sum; 84 } 85 } 86 87 } 88 89 void solver() 90 { 91 res = 11; 92 dfs(sx, sy, 1); 93 94 } 95 int main() 96 { 97 while(cin >> w >> h) 98 { 99 if(w == 0 && h == 0) 100 break; 101 //input 102 for(int i = 0; i < h; ++i) 103 { 104 for(int j = 0; j < w; ++j) 105 { 106 cin >> MAP[i][j]; 107 if(MAP[i][j] == 2) 108 { 109 sx = j; 110 sy = i; 111 } 112 if(MAP[i][j] == 3) 113 { 114 ex = j; 115 ey = i; 116 } 117 } 118 } 119 //solver 120 solver(); 121 //output 122 if(res > 10) 123 cout << -1 << endl; 124 else 125 cout << res << endl; 126 } 127 128 return 0; 129 }