原题链接:http://poj.org/problem?id=3009
暴力DFS + 回溯。注意行和列不要搞反,并且当搜索深度大于10的时候直接返回。
View Code
1 #include <stdio.h> 2 #include <string.h> 3 4 int r, c, ans; 5 int g[25][25]; 6 7 inline int min(int x, int y){return x < y ? x : y;} 8 9 int checkup(int x, int y) 10 { 11 if(y - 1 > 0 && g[y - 1][x] == 1) 12 return 0; 13 int i; 14 for(i = y - 1; i > 0; i --) 15 { 16 if(g[i][x] == 3) 17 return -1; 18 if(g[i][x] == 1) 19 { 20 g[i][x] = 0; 21 return i + 1; 22 } 23 } 24 return 0; 25 } 26 27 int checkdown(int x, int y) 28 { 29 if(y + 1 <= r && g[y + 1][x] == 1) 30 return 0; 31 int i; 32 for(i = y + 1; i <= r; i ++) 33 { 34 if(g[i][x] == 3) 35 return -1; 36 if(g[i][x] == 1) 37 { 38 g[i][x] = 0; 39 return i - 1; 40 } 41 } 42 return 0; 43 } 44 45 int checkleft(int x, int y) 46 { 47 if(x - 1 > 0 && g[y][x - 1] == 1) 48 return 0; 49 int i; 50 for(i = x - 1; i > 0; i --) 51 { 52 if(g[y][i] == 3) 53 return -1; 54 if(g[y][i] == 1) 55 { 56 g[y][i] = 0; 57 return i + 1; 58 } 59 } 60 return 0; 61 } 62 63 int checkright(int x, int y) 64 { 65 if(x + 1 <= c && g[y][x + 1] == 1) 66 return 0; 67 int i; 68 for(i = x + 1; i <= c; i ++) 69 { 70 if(g[y][i] == 3) 71 return -1; 72 if(g[y][i] == 1) 73 { 74 g[y][i] = 0; 75 return i - 1; 76 } 77 } 78 return 0; 79 } 80 81 void dfs(int cx, int cy, int d) 82 { 83 if(d >= 10) 84 return ; 85 int up = checkup(cx, cy); 86 if(up == -1) 87 { 88 ans = (ans == -1 ? d + 1 : min(ans, d + 1)); 89 return ; 90 } 91 else if(up != 0) 92 { 93 dfs(cx, up, d + 1); 94 g[up - 1][cx] = 1; 95 } 96 97 int down = checkdown(cx, cy); 98 if(down == -1) 99 { 100 ans = (ans == -1 ? d + 1 : min(ans, d + 1)); 101 return ; 102 } 103 else if(down != 0) 104 { 105 dfs(cx, down, d + 1); 106 g[down + 1][cx] = 1; 107 } 108 109 int left = checkleft(cx, cy); 110 if(left == -1) 111 { 112 ans = (ans == -1 ? d + 1 : min(ans, d + 1)); 113 return ; 114 } 115 else if(left != 0) 116 { 117 dfs(left, cy, d + 1); 118 g[cy][left - 1] = 1; 119 } 120 121 int right = checkright(cx, cy); 122 if(right == -1) 123 { 124 ans = (ans == -1 ? d + 1 : min(ans, d + 1)); 125 return ; 126 } 127 else if(right != 0) 128 { 129 dfs(right, cy, d + 1); 130 g[cy][right + 1] = 1; 131 } 132 } 133 134 int main() 135 { 136 int i, j, sx, sy; 137 while(scanf("%d%d", &c, &r), r + c) 138 { 139 for(i = 1; i <= r; i ++) 140 { 141 for(j = 1; j <= c; j ++) 142 { 143 scanf("%d", &g[i][j]); 144 if(g[i][j] == 2) 145 sx = j, sy = i; 146 } 147 } 148 ans = -1; 149 dfs(sx, sy, 0); 150 printf("%d\n", ans); 151 } 152 return 0; 153 }