USACO 5.2 Snail Trails(DFS)
DFS,1Y啊。。
1 /* 2 ID: cuizhe 3 LANG: C++ 4 TASK: snail 5 */ 6 #include <iostream> 7 #include <cstdio> 8 #include <cstring> 9 #include <queue> 10 #include <map> 11 #include <cmath> 12 #include <algorithm> 13 using namespace std; 14 int a[4] = {0,1,-1,0}; 15 int b[4] = {1,0,0,-1}; 16 int o[201][201]; 17 int n,ans; 18 void dfs(int x,int y,int pos,int step) 19 { 20 int i; 21 ans = max(step,ans); 22 if(x+a[pos] <= n&&x+a[pos] >= 1&&y+b[pos] >= 1&&y+b[pos] <= n&&!o[x+a[pos]][y+b[pos]]) 23 { 24 o[x+a[pos]][y+b[pos]] = 2; 25 dfs(x+a[pos],y+b[pos],pos,step+1); 26 o[x+a[pos]][y+b[pos]] = 0; 27 } 28 else if(x+a[pos] <= n&&x+a[pos] >= 1&&y+b[pos] >= 1&&y+b[pos] <= n&&o[x+a[pos]][y+b[pos]] == 2) 29 { 30 return ; 31 } 32 else 33 { 34 for(i = 0; i < 4; i ++) 35 { 36 if(pos == 0||pos == 3) 37 { 38 if(i == 1||i == 2) 39 { 40 if(x+a[i] <= n&&x+a[i] >= 1&&y+b[i] >= 1&&y+b[i] <= n&&!o[x+a[i]][y+b[i]]) 41 { 42 o[x+a[i]][y+b[i]] = 2; 43 dfs(x+a[i],y+b[i],i,step+1); 44 o[x+a[i]][y+b[i]] = 0; 45 } 46 } 47 } 48 else 49 { 50 if(i == 0||i == 3) 51 { 52 if(x+a[i] <= n&&x+a[i] >= 1&&y+b[i] >= 1&&y+b[i] <= n&&!o[x+a[i]][y+b[i]]) 53 { 54 o[x+a[i]][y+b[i]] = 2; 55 dfs(x+a[i],y+b[i],i,step+1); 56 o[x+a[i]][y+b[i]] = 0; 57 } 58 } 59 } 60 } 61 } 62 return ; 63 } 64 int main() 65 { 66 int m,i,j,len,sv,ev; 67 char ch[101]; 68 freopen("snail.in","r",stdin); 69 freopen("snail.out","w",stdout); 70 scanf("%d%d",&n,&m); 71 for(i = 0; i < m; i ++) 72 { 73 scanf("%s",ch); 74 len = strlen(ch); 75 sv = ch[0]-'A' + 1; 76 ev = 0; 77 for(j = 1; j < len; j ++) 78 { 79 ev = ev*10 + ch[j]- '0'; 80 } 81 o[sv][ev] = 1; 82 } 83 o[1][1] = 2; 84 dfs(1,1,0,1); 85 dfs(1,1,1,1); 86 printf("%d\n",ans); 87 return 0; 88 }