题目: http://poj.org/problem?id=3009
很简单的一个题,调试了好久。。
1 #include <stdio.h> 2 #include <string.h> 3 4 int n, m, maze[30][30], ans; 5 int start_x, start_y, end_x, end_y; 6 int dirc[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; 7 8 void dfs(int x, int y, int step, int dir) 9 { 10 if(step > 10 || maze[x][y] == -1)return; 11 if(x == end_x && y == end_y) 12 { 13 if(ans == -1 || step < ans) 14 ans = step; 15 return; 16 } 17 int nx = x + dirc[dir][0]; 18 int ny = y + dirc[dir][1]; 19 if(maze[nx][ny] != 1) 20 { 21 dfs(nx, ny, step, dir); 22 return; 23 } 24 else if(maze[nx][ny] == 1) 25 { 26 maze[nx][ny] = 0; 27 for(int d = 0; d < 4; d++) 28 { 29 int xx = x + dirc[d][0]; 30 int yy = y + dirc[d][1]; 31 if(maze[xx][yy] != 1) 32 dfs(xx, yy, step+1, d); 33 } 34 maze[nx][ny] = 1; 35 } 36 } 37 38 int main() 39 { 40 while(scanf("%d %d", &m, &n) != EOF) 41 { 42 if(n == 0 && m == 0)break; 43 memset(maze, -1, sizeof(maze)); 44 for(int i = 1; i <= n; i++) 45 { 46 for(int j = 1; j <= m; j++) 47 { 48 scanf("%d", &maze[i][j]); 49 if(maze[i][j] == 2) 50 { 51 start_x = i; 52 start_y = j; 53 } 54 if(maze[i][j] == 3) 55 { 56 end_x = i; 57 end_y = j; 58 } 59 } 60 } 61 ans = -1; 62 for(int d = 0; d < 4; d++) 63 { 64 int nx = start_x + dirc[d][0]; 65 int ny = start_y + dirc[d][1]; 66 if(maze[nx][ny] != 1) 67 dfs(nx, ny, 1, d); 68 } 69 printf("%d ", ans); 70 } 71 return 0; 72 }