Uva--639 (回溯暴力)
2014-07-15 09:45:37
题意&思路:不说啥了,写挫了- -.
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 7 int n,num,used[5][5],tmax; 8 char g[5][5]; 9 10 void Dfs(int r,int c,int cnt){ 11 tmax = max(tmax,cnt); 12 int flag = 1; 13 for(int i = r + 1; i < n; ++i){ 14 if(g[i][c] == 'X') break; 15 if(g[i][c] == 'G'){ flag = 0; break;} 16 } 17 for(int i = r - 1; i >= 0; --i){ 18 if(g[i][c] == 'X') break; 19 if(g[i][c] == 'G'){ flag = 0; break;} 20 } 21 for(int j = c + 1; j < n; ++j){ 22 if(g[r][j] == 'X') break; 23 if(g[r][j] == 'G'){ flag = 0; break;} 24 } 25 for(int j = c - 1; j >= 0; --j){ 26 if(g[r][j] == 'X') break; 27 if(g[r][j] == 'G'){ flag = 0; break;} 28 } 29 int tag = 0,tr,tc; 30 for(int i = 0; i < n; ++i){ 31 for(int j = 0; j < n; ++j){ 32 if(g[i][j] == '.' && !used[i][j]){ 33 tr = i; 34 tc = j; 35 tag = 1; 36 break; 37 } 38 } 39 if(tag) break; 40 } 41 if(flag){ 42 tmax = max(tmax,cnt + 1); 43 if(tag){ 44 used[tr][tc] = 1; 45 g[r][c] = 'G'; 46 Dfs(tr,tc,cnt + 1); 47 used[tr][tc] = 0; 48 g[r][c] = '.'; 49 } 50 } 51 if(tag){ 52 used[tr][tc] = 1; 53 Dfs(tr,tc,cnt); 54 used[tr][tc] = 0; 55 } 56 } 57 58 int main(){ 59 while(scanf("%d",&n) == 1 && n){ 60 for(int i = 0; i < n; ++i) 61 scanf("%s",g[i]); 62 memset(used,0,sizeof(used)); 63 tmax = 0; 64 for(int i = 0; i < n; ++i) 65 for(int j = 0; j < n; ++j) 66 if(g[i][j] == '.'){ 67 used[i][j] = 1; 68 Dfs(i,j,0); 69 break; 70 } 71 printf("%d\n",tmax); 72 } 73 return 0; 74 }